Skip to content
AgileLogics
6 min read

Maps

Prerequisites: Lists, Working with nullable values

A map stores key-value pairs: you look up a value by its key instead of by position. Other languages call this a dictionary.

Real-world analogy: a map is a contacts list — you find a phone number by the person's name, not by where it is in the list.

Creating maps

to pairs a key with a value:

val ages = mapOf("Ada" to 36, "Linus" to 28)           // read-only
val stock = mutableMapOf("apples" to 10)               // can change

Reading values

Looking up a key returns a nullable value, since the key might not exist:

fun main() {
    val ages = mapOf("Ada" to 36, "Linus" to 28)

    println(ages["Ada"])
    println(ages["Grace"])
    println(ages.getOrDefault("Grace", 0))
    println(ages["Grace"] ?: 0)
    println(ages.containsKey("Linus"))
    println(ages.keys)
    println(ages.values)
    println(ages)
}
36
null
0
0
true
[Ada, Linus]
[36, 28]
{Ada=36, Linus=28}

Maps created with mapOf and mutableMapOf keep the order in which keys were added.

Changing a mutable map

fun main() {
    val stock = mutableMapOf("apples" to 10, "pears" to 4)

    stock["plums"] = 7
    stock["apples"] = 12
    stock.remove("pears")
    stock["apples"] = (stock["apples"] ?: 0) + 1

    for ((fruit, count) in stock) {
        println("$fruit: $count")
    }
}
apples: 13
plums: 7

for ((key, value) in map) unpacks each entry.

Common mistakes

  • Using a looked-up value as non-null: ages["Ada"] + 1 doesn't compile, because the lookup is an Int?. Use ?: 0, getOrDefault, or getValue (which throws if the key is missing).
  • Using mapOf when you need to add entries later — use mutableMapOf.

Practice

Count how many times each word appears in listOf("red", "blue", "red", "green", "red") using a mutable map, and print the map.

Show solution
fun main() {
    val words = listOf("red", "blue", "red", "green", "red")
    val counts = mutableMapOf<String, Int>()

    for (word in words) {
        counts[word] = (counts[word] ?: 0) + 1
    }

    println(counts)
}
{red=3, blue=1, green=1}