Kotlin Map and MutableMap (with Examples)

Kotlin course · Collections · Lesson 30 of 51

A map stores key–value pairs. You look up a value by its key, like finding a phone number by a person’s name. Keys are unique; values can repeat.

Creating maps

fun main() {
    val capitals = mapOf("India" to "New Delhi", "Japan" to "Tokyo", "France" to "Paris")
    val stock = mutableMapOf("pen" to 40, "notebook" to 12)

    println(capitals)
    println(stock)
    println(capitals.size)
}

Output:

{India=New Delhi, Japan=Tokyo, France=Paris}
{pen=40, notebook=12}
3

"India" to "New Delhi" creates a Pair. A map is a collection of these pairs.

Reading values

fun main() {
    val capitals = mapOf("India" to "New Delhi", "Japan" to "Tokyo")

    println(capitals["India"])                  // String? (null if missing)
    println(capitals["Brazil"])
    println(capitals.getOrDefault("Brazil", "Unknown"))
    println(capitals.getOrElse("Brazil") { "Not in list" })
    println("Japan" in capitals)                // checks keys
    println(capitals.containsValue("Tokyo"))
}

Output:

New Delhi
null
Unknown
Not in list
true
true

map[key] returns a nullable value, because the key might not exist. Handle it with ?:, getOrDefault or getOrElse. Avoid getValue() unless you’re sure the key is there: it throws an exception if it isn’t.

Adding, updating and removing (MutableMap)

fun main() {
    val stock = mutableMapOf("pen" to 40, "notebook" to 12)

    stock["eraser"] = 25           // add
    stock["pen"] = 35              // update
    stock["notebook"] = stock.getOrDefault("notebook", 0) + 10
    stock.remove("eraser")
    stock.putIfAbsent("ruler", 8)

    println(stock)
}

Output:

{pen=35, notebook=22, ruler=8}

Looping over a map

fun main() {
    val prices = mapOf("Tea" to 20, "Coffee" to 35, "Juice" to 50)

    for ((item, price) in prices) {
        println("$item: ₹$price")
    }
    println(prices.keys)
    println(prices.values)
    println(prices.values.sum())
}

Output:

Tea: ₹20
Coffee: ₹35
Juice: ₹50
[Tea, Coffee, Juice]
[20, 35, 50]
105

Filtering and transforming

fun main() {
    val marks = mapOf("Asha" to 91, "Ravi" to 64, "Meera" to 78, "Kabir" to 45)

    println(marks.filter { (_, m) -> m >= 75 })
    println(marks.filterKeys { it.startsWith("K") })
    println(marks.mapValues { (_, m) -> if (m >= 50) "Pass" else "Fail" })
    println(marks.maxBy { it.value }.key)
    println(marks.toList().sortedByDescending { it.second })
}

Output:

{Asha=91, Meera=78}
{Kabir=45}
{Asha=Pass, Ravi=Pass, Meera=Pass, Kabir=Fail}
Asha
[(Asha, 91), (Meera, 78), (Ravi, 64), (Kabir, 45)]

Counting with a map

A classic use: count how often each item appears.

fun main() {
    val words = "the cat and the dog and the bird".split(" ")

    val counts = mutableMapOf<String, Int>()
    for (w in words) counts[w] = (counts[w] ?: 0) + 1
    println(counts)

    println(words.groupingBy { it }.eachCount())   // the same, in one line
}

Output:

{the=3, cat=1, and=2, dog=1, bird=1}
{the=3, cat=1, and=2, dog=1, bird=1}

Building maps from lists

fun main() {
    val names = listOf("Asha", "Ravi", "Meera")
    println(names.associateWith { it.length })
    println(names.associateBy { it.first() })
    println(names.withIndex().associate { it.index to it.value })
}

Output:

{Asha=4, Ravi=4, Meera=5}
{A=Asha, R=Ravi, M=Meera}
{0=Asha, 1=Ravi, 2=Meera}

For more ways to turn a list into a map, see the List to map lesson.

Map types and order

FunctionOrder
mapOf, mutableMapOfinsertion order (LinkedHashMap)
hashMapOfno guaranteed order
sortedMapOfsorted by key

Common mistakes

  • Assuming map[key] isn’t null: it’s always nullable. Use ?: or getOrDefault.
  • Duplicate keys in mapOf: the last one wins silently: mapOf("a" to 1, "a" to 2) is {a=2}.
  • Mutating a read-only map: mapOf can’t change. Use mutableMapOf or toMutableMap().

Exercise

Build a simple phone book: start with three contacts, update one number, look up an existing and a missing name safely, and print everyone in alphabetical order.

fun main() {
    val phoneBook = mutableMapOf(
        "Ravi" to "98100 11111",
        "Asha" to "98200 22222",
        "Meera" to "98300 33333"
    )
    phoneBook["Ravi"] = "98100 99999"

    println(phoneBook["Asha"] ?: "Not found")
    println(phoneBook["Zoya"] ?: "Not found")

    for ((name, number) in phoneBook.toSortedMap()) println("$name: $number")
}

Output:

98200 22222
Not found
Asha: 98200 22222
Meera: 98300 33333
Ravi: 98100 99999

FAQ

How do I create a map in Kotlin?

mapOf("a" to 1, "b" to 2) for a read-only map, mutableMapOf() for one you can change.

How do I get a value from a map safely?

map[key] ?: default, map.getOrDefault(key, default) or map.getOrElse(key) { … }.

What’s the difference between Map and HashMap in Kotlin?

Map is the read-only interface. HashMap is one mutable implementation. mutableMapOf() gives you a LinkedHashMap, which keeps insertion order.

WhatsApp us📞 Call now