Creating maps
- Kotlin course
- Beginner
- Lesson 67/116
- 5 min
Learn to create maps with mapOf and mutableMapOf.
Creating maps: mapOf and mutableMapOf
A map binds keys to values. mapOf returns a read-only map, while mutableMapOf gives a mutable map. Pairs are written with to: "key" to value.
val ages = mapOf("Ava" to 25, "Liam" to 30)
println(ages["Ava"]) // 25Keys are unique: if you write the same key twice, the second value overwrites the first. The inferred type looks like Map<String, Int>.
keys, values and entries
You get all keys of a map with keys, all values with values, and key-value pairs with entries. You can iterate them like a list.
val ages = mapOf("Ava" to 25, "Liam" to 30)
ages.keys // [Ava, Liam]
ages.values // [25, 30]
ages.entries // [Ava=25, Liam=30]entries returns a set of Entry<K, V>. Each entry has .key and .value fields.
Practice Print a two-person age map
Create a mapOf("Ava" to 25, "Liam" to 30) and print it with println.
Starter code
fun main() {
// Create a map of two people's ages and print it
}Sample solution
fun main() {
val ages = mapOf("Ava" to 25, "Liam" to 30)
println(ages)
}Expected output
{Ava=25, Liam=30}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: read-only map
val ages = ____("Ava" to 25, "Liam" to 30)
val ages = mapOf("Ava" to 25, "Liam" to 30)
Explanation: mapOf("..." to ...) returns a read-only map.
2 How many elements does mapOf("a" to 1, "a" to 2) have?
- 2 (both kept)
- Throws an exception
- 1 (second a overwrites) Correct answer
- 0 (error)
Explanation: Keys are unique; the second value overwrites the first.
3 Match map expression to role
| Term | Meaning |
|---|---|
mapOf(...) |
Read-only map |
mutableMapOf(...) |
Mutable map |
to |
Key-value connector |
keys |
All keys |