Reading — step 1 of 5
Learn
~1 min readCollections
Maps work the same way — read-only Map<K, V> and mutable MutableMap<K, V>:
val ages = mapOf(
"Alice" to 30,
"Bob" to 25,
)
println(ages["Alice"]) // 30
println(ages.containsKey("Carol")) // false
val mutable = mutableMapOf<String, Int>()
mutable["Carol"] = 40
mutable.remove("Carol")
The to operator creates a Pair<K, V>. The mapOf function takes any number of pairs.
map[key] returns V? — null if missing. The getOrDefault(key, default) form is convenient for counters:
val counts = mutableMapOf<String, Int>()
for (w in words) {
counts[w] = counts.getOrDefault(w, 0) + 1
}
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…