Thuta Learning
Kotlin
IntermediateProgrammingBeginner

Collections (Maps)

KotlinLesson 1330 min

What you'll walk away with

  • Create read-only and mutable maps and read, add, overwrite and remove entries
  • Explain why map[key] returns a nullable value and pick between getOrDefault, getOrElse and getValue
  • Loop over entries with destructuring and build new maps with groupBy, filter and mapValues
  • Tell a read-only Map view from a truly independent copy

Explain it simply

Explain it simply

A map is a lookup table. Think of a paper phone book: you do not read it from page one to find Aye, you jump straight to the name and read the number beside it. In Kotlin the name is the key, the number is the value, and the whole book is a Map<String, String>.

Every key appears at most once, so "Aye" can have only one number at a time, although two different keys may share the same value. A map answers one question very well: given this key, what is its value? When there is no such key the answer is null, and the type system makes you deal with that.

Problem → Why → Solution

The problem: slow lookups, and missing keys that quietly give null

Picture keeping names in one list and ages in another, then finding someone by walking the first list until the name matches. It works for three people, but every lookup scans the whole list and the two lists must be kept in the same order by hand. A map removes both problems, yet it brings its own surprise: a key that is missing, or spelled differently, does not crash. It quietly gives you null.

The code below shows both pains. The first half searches parallel lists. The second half asks a map for "alice" when the key is "Alice", and the compiler refuses to let you add 1 to the answer, because the answer might be null.

lookup-problems.kt
fun main() {
    // Parallel lists: lookup by scanning, order kept in sync by hand
    val names = listOf("Alice", "Bob")
    val ages = listOf(30, 25)
    val index = names.indexOf("Bob")
    println(ages[index])

    // A map fixes that, but a missing key gives null, not 0
    val ageMap = mapOf("Alice" to 30, "Bob" to 25)
    val next = ageMap["alice"] + 1   // compile error: the key might be missing
    println(next)
}

Why does the map hand back null?

A Map cannot know in advance which keys you will ask for, so get() has two honest answers: the value, or nothing. Kotlin models "nothing" as null and gives the result the type Int?, which is why ageMap["alice"] + 1 fails to compile with "operator call is prohibited on a nullable receiver of type 'Int?'". Java's HashMap also returns null, but nothing forces you to notice. In Kotlin you must decide what a missing key means: a default, an error, or a branch.

Core concept: Map<K, V> is read-only, MutableMap<K, V> can change

Kotlin splits the map idea into two interfaces. Map<K, V> is the read-only view: you can look things up, loop and count, but there is no put or remove. MutableMap<K, V> extends it with put, remove, clear and the [key] = value assignment. mapOf(...) gives you a Map, mutableMapOf(...) gives you a MutableMap, and the pairs are written with the infix function to, as in "Alice" to 30, which simply builds a Pair.

Reading is where the type system helps most. map[key] is shorthand for get(key) and returns V?, because the key may be absent. You then choose what a missing key means. getOrDefault(key, fallback) returns a fallback value, getOrElse(key) { ... } computes the fallback only when it is needed, and getValue(key) throws NoSuchElementException when the key is missing, which is right when absence is a bug. withDefault { ... } attaches a default to the map, but it only affects getValue(); the square-bracket form still returns null.

Order and equality are worth knowing. mapOf and mutableMapOf keep entries in insertion order, so looping prints them in the order you wrote them. A HashMap makes no such promise, so never rely on its order. Two maps are equal when they hold the same keys with equal values, whatever the order. Keys are found by equals() and hashCode(), so String, Int and data class keys behave well, while a key object that you mutate after inserting it can become impossible to find again.

Finally, remember that Map is a view, not a freezer. If a MutableMap is passed to a function that expects a Map, the function cannot change it, but the owner still can, and the function sees those changes. Use toMap() when you need an independent snapshot. For everyday transformation, filter, mapValues, groupBy and associateBy return brand-new maps instead of mutating the old one.

CallWhen the key is missingUse it when
map[key] / get(key)Returns nullYou want to branch on presence
getOrDefault(key, d)Returns dA fixed fallback is enough
getOrElse(key) { ... }Runs the lambdaThe fallback is costly to compute
getValue(key)Throws NoSuchElementExceptionA missing key is a bug
text
Lookup in mapOf("Alice" to 30, "Bob" to 25)
-------------------------------------------
  key        lookup        result
  --------   ----------    ----------------
  "Alice" -> found      -> 30
  "alice" -> not found  -> null   (type Int?)
  "Bob"   -> found      -> 25
Mental model: a phone book with unique names
  1. Hand the map a key
  2. The map finds the matching entry
  3. Found: you get its value
  4. Missing: null or your fallback

The V? type is the map telling you it is not sure the key exists, so the fallback is always your decision.

General pattern

kotlin
val readOnly: Map<K, V> = mapOf(key1 to value1, key2 to value2)
val editable: MutableMap<K, V> = mutableMapOf()

editable[key] = value                  // add a new entry or overwrite
val found: V? = readOnly[key]          // null when the key is missing
val safe: V = readOnly.getOrDefault(key, fallback)

for ((key, value) in readOnly) {
    // use key and value
}

Pairs are written key to value. Reading with [key] gives V?, while getOrDefault gives a plain V. for ((key, value) in map) splits every entry into its key and value, which is called destructuring.

Example: build an age map and look one person up

This example builds a read-only map of two people and reads one age with the square-bracket operator. Because ageMap["Alice"] is an Int?, the string template prints either the number or the word null. Run it, then change the key to "alice" and watch what is printed.

kotlin
fun main() {
    val ageMap = mapOf(
        "Alice" to 30,
        "Bob" to 25
    )

    println("Alice's age is ${ageMap["Alice"]}")
}

Code breakdown

  1. Create the mapval ageMap = mapOf(

    mapOf creates a read-only Map<String, Int>. The compiler infers both type parameters from the pairs, so you never write them out. val means the variable cannot be reassigned; whether the entries can change is decided by the type, and a Map cannot be changed through that type.

  2. Write a pair with to"Alice" to 30,

    to is an ordinary infix function that returns Pair("Alice", 30). mapOf takes pairs, so each line is one entry with the key on the left and the value on the right. Keys must be unique: if you wrote "Alice" twice, the later value would win.

  3. Last entry"Bob" to 25

    Entries are stored in the order written, so printing the map shows Alice first and Bob second. A trailing comma after the last pair is allowed, which keeps adding an entry a one-line change.

  4. Look up a keyageMap["Alice"]

    The square brackets call get("Alice"). The result type is Int?, not Int, because the key could be missing. Here the key exists, so the value is 30.

  5. Use it in a templateprintln("Alice's age is ${ageMap["Alice"]}")

    Inside a string template, ${...} may hold any expression, even one with its own quotes. If the lookup returned null, the template would print the word null instead of failing, which is exactly why a silent typo is easy to miss.

You should see
Alice's age is 30
What happens during a lookup
  1. Call map[key]
  2. The map compares keys with equals() and hashCode()
  3. Is there a matching entry?

Found

returns the value (type V?)

Not found

returns null, or your default with getOrDefault

Reading safely: null, defaults and getValue

Let us compare the ways to read side by side. stock["kiwi"] returns null, because its type is Int?. getOrDefault("kiwi", 0) returns 0, and getOrElse("kiwi") { -1 } runs the lambda only when the key is missing. "kiwi" in stock is a plain boolean. withDefault deserves extra care: known.getValue("kiwi") gives 0, yet known["kiwi"] still gives null, so you only benefit from the default when you call getValue. On an ordinary map, getValue("kiwi") throws NoSuchElementException with the message "Key kiwi is missing in the map."

reading.kt
fun main() {
    val stock = mapOf("apple" to 12, "pear" to 0, "plum" to 7)

    println(stock["apple"])                  // 12
    println(stock["kiwi"])                   // null
    println(stock.getOrDefault("kiwi", 0))   // 0
    println(stock.getOrElse("kiwi") { -1 })  // -1
    println("kiwi" in stock)                 // false

    val known = stock.withDefault { 0 }
    println(known["kiwi"])                   // null: [] ignores the default
    println(known.getValue("kiwi"))          // 0
    try {
        stock.getValue("kiwi")
    } catch (e: NoSuchElementException) {
        println("getValue failed: " + e.message)
    }
}

Changing a map and building new ones

On a MutableMap, orders["tea"] = 2 adds a new entry when the key is absent and overwrites the value when it is present. The counting pattern "add one, starting from zero" is counts[w] = counts.getOrDefault(w, 0) + 1. getOrPut(key) { ... } computes and stores a value only when the key is missing, then returns it. for ((item, qty) in orders) splits each entry into two named variables. groupBy turns a list into a Map whose values are lists, one per key.

changing.kt
fun main() {
    val orders = mutableMapOf<String, Int>()
    orders["tea"] = 2
    orders["coffee"] = 1
    orders["tea"] = (orders["tea"] ?: 0) + 3   // overwrite the old value
    orders.getOrPut("cake") { 4 }              // inserted only because it was missing
    orders.remove("coffee")
    for ((item, qty) in orders) println("$item x $qty")

    val words = listOf("kotlin", "java", "kotlin", "go", "java", "kotlin")
    val counts = mutableMapOf<String, Int>()
    for (w in words) counts[w] = counts.getOrDefault(w, 0) + 1
    println(counts)

    val byLength = words.distinct().groupBy { it.length }
    println(byLength)
}

A read-only view versus an independent copy

A Map type only promises "you cannot change it through this reference"; it does not promise that the data never changes. Below, view and backing are the same object, so changes made through backing are visible in view. toMap() returns a new map that copies the entries at that moment, so later changes do not touch the snapshot.

view-vs-copy.kt
fun main() {
    val backing = mutableMapOf("a" to 1)
    val view: Map<String, Int> = backing    // same object, read-only type
    backing["b"] = 2
    println(view)                           // {a=1, b=2}
    val snapshot = backing.toMap()          // independent copy
    backing["c"] = 3
    println(snapshot)                       // {a=1, b=2}
    println(backing == mapOf("c" to 3, "b" to 2, "a" to 1))   // true: order is ignored
}

In real projects

Where this shows up in real projects

Maps appear wherever data is looked up by name. A settings screen keeps preferences as a Map<String, String>, a web server hands your handler the query parameters and headers as maps, and a shopping cart is often a Map<ProductId, Int> of quantities. When rows arrive from a database or a JSON array as a list, associateBy { it.id } turns them into a map once, and every later lookup is a single call instead of a find over the whole list.

Counting and grouping are the other big uses. Counting words, errors per status code or visits per page is a mutable map plus getOrDefault. Grouping orders by customer or log lines by level is groupBy, which returns a Map<K, List<V>> for you. Two cautions from production code: a plain mutable map must not be modified from several threads at once, so use a ConcurrentHashMap or keep the map on one thread, and a map that only ever grows, such as a cache, needs a size limit or an expiry policy.

Common mistakes

Common mistakes

1. Doing arithmetic on a lookup result

val total = prices["tea"] * 3 does not compile, because prices["tea"] is an Int?. The tempting fix, !!, turns a missing key into a crash at runtime. Prefer (prices["tea"] ?: 0) * 3 or getOrDefault, and use getValue only when absence really is a bug.

2. Expecting mapOf to be editable

val m = mapOf("a" to 1) followed by m["b"] = 2 fails with "no 'set' operator method providing array access", because mapOf returns a read-only Map. Create the map with mutableMapOf, or build a new map with m + ("b" to 2).

3. Removing entries while looping over them

Calling remove inside for (key in map.keys) changes the map under the iterator, and the next step throws ConcurrentModificationException. Remove with map.entries.removeAll { ... } or build a filtered copy with filterValues, as the snippet below shows.

4. Overlooking spelling or case differences in keys

"alice" and "Alice" are different keys, so inserting both creates two entries instead of overwriting. Normalise user-typed text with trim() and lowercase() before using it as a key.

remove-while-iterating.kt
fun main() {
    val first = mutableMapOf("a" to 5, "b" to -1, "c" to 7)
    try {
        for (key in first.keys) if (first.getValue(key) < 0) first.remove(key)
    } catch (e: ConcurrentModificationException) {
        println("crashed with " + e::class.simpleName)
    }
    val second = mutableMapOf("a" to 5, "b" to -1, "c" to 7)
    second.entries.removeAll { it.value < 0 }
    println(second)
    println(mapOf("a" to 5, "b" to -1, "c" to 7).filterValues { it >= 0 })
}

Best practices

Best practices

  • Expose maps as read-only Map in function parameters and return types, and keep the MutableMap private to the class that owns it.
  • Choose the missing-key behaviour on purpose: getOrDefault for a fixed fallback, getValue when absence is a bug, and an explicit null check when absence is normal.
  • Use a data class or an enum as the key instead of a glued-together string such as "user-42-admin", so equals and hashCode do the work for you.

Mini challenge

Mini challenge: word counter

Build a small word-frequency tool: count how often each word appears in a sentence, then report the most frequent words and the words that appear only once.

  • countWords(text) returns a Map<String, Int>, ignoring case and extra spaces
  • Print the top 3 words as "word: count", highest first and A-Z on ties
  • Print the count for a word that is not in the text, using getOrDefault so the answer is 0
  • Use groupBy to find the words that appear exactly once and print them sorted
wordcount.kt
fun countWords(text: String): Map<String, Int> {
    // TODO: lowercase the text, split it on spaces and skip blank pieces
    // TODO: count every word in a MutableMap, then return it
}

fun main() {
    val counts = countWords("To be or not to be that is the question to")
    // TODO: print the top 3 as "word: count" (highest first, ties A-Z)
    // TODO: print the count of "cat" so that a missing word shows 0
    // TODO: print the sorted words that appear exactly once
}

Expected: The program prints these five lines: to: 3 be: 2 is: 1 0 [is, not, or, question, that, the]

Show hint

Sort the entries with sortedWith(compareBy({ -it.value }, { it.key })): the first selector orders by count, highest first, and the second breaks ties alphabetically. For groupBy, group the keys by their count with counts.keys.groupBy { counts.getValue(it) } and then read the group for 1.

Show solution
wordcount.kt
fun countWords(text: String): Map<String, Int> {
    val counts = mutableMapOf<String, Int>()
    for (word in text.lowercase().split(" ").filter { it.isNotBlank() }) {
        counts[word] = counts.getOrDefault(word, 0) + 1
    }
    return counts
}

fun main() {
    val counts = countWords("To be or not to be that is the question to")
    val ranked = counts.entries.sortedWith(compareBy({ -it.value }, { it.key }))
    for ((word, n) in ranked.take(3)) println("$word: $n")
    println(counts.getOrDefault("cat", 0))
    val byCount = counts.keys.groupBy { counts.getValue(it) }
    println(byCount.getValue(1).sorted())
}

Quick quiz 1 / 3

What does println(mapOf("a" to 1)["b"]) print?

Quick quiz 2 / 3

Given val m = mapOf("a" to 1).withDefault { 0 }, which expression gives 0 for the missing key "z"?

Quick quiz 3 / 3

After val scores = mapOf("Aye" to 70), what happens with scores["Kyaw"] = 85?

What to remember

  • Map<K, V> is read-only, MutableMap<K, V> is editable, and pairs are written key to value with the infix function to.
  • map[key] returns V? because the key may be missing: choose getOrDefault, getOrElse, getValue or an explicit null check on purpose.
  • withDefault only affects getValue(); square-bracket access still returns null.
  • Loop with for ((key, value) in map), build new maps with groupBy, filter and mapValues, and never remove entries from the map you are iterating over.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Collections (Maps) | Thuta Learning