Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 134 ยท Collections

Maps

Learn Kotlin maps: mapOf and mutableMapOf, safe lookups, getOrPut, iterating entries, filtering, merging, counting with groupingBy, sorting and LinkedHashMap vs HashMap, with runnable code.

A map stores associations: a key points to a value. Phone books, price lists, configuration settings, counters per word and caches are all maps. You give the map a key and it gives you back the value in (usually) constant time, no matter how many entries it holds. Other languages call this a dictionary, hash table or associative array.

In this lesson you learn how to create maps, look values up safely, change and iterate them, and handle the two jobs you will meet constantly: counting things and grouping things. Read Collections Overview first if you have not; the idea of read-only versus mutable collections applies to maps too.

Creating and reading

You build a map from key to value pairs. The to is an ordinary infix function that creates a Pair.

Kotlin A first map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is {France=Paris, Japan=Tokyo, Peru=Lima}, 3, Tokyo, null, true, true, [France, Japan, Peru] and [Paris, Tokyo, Lima]. The key point is capitals["Mars"]: reading with square brackets returns null for a missing key, so the type of the expression is String?. "Peru" in capitals checks the keys.

Safe lookups

Because the plain lookup can be null, you need a plan for missing keys:

Kotlin Handling missing keys (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first five lines are 12, -1, 0, 99 and 0. After that the program crashes with Exception in thread "main" java.util.NoSuchElementException: Key kiwi is missing in the map. followed by a stack trace. getValue returns a non-null value and throws when the key is absent. Use it when a missing key is a bug; use ?:, getOrDefault or getOrElse when absence is normal. The difference between getOrDefault (the default is computed eagerly) and getOrElse (a lambda that runs only when needed) matters if the default is expensive.

A map can store null values (Map<String, Int?>). Then map[key] returning null is ambiguous: the key might be missing or its value might be null. Use containsKey(key) to tell the two cases apart.

Changing a mutable map

Kotlin MutableMap operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get {tea=5, coffee=4, milk=2, cake=6}, 6, {tea=5, cake=7}, {tea=6, cake=7, juice=4}, [tea, cake, juice, water] and true. Assigning to a key either adds a new entry or replaces the old value. put returns the previous value (or null), which is why the second call printed 6. += with another map merges it in, and later values win for keys that exist in both.

getOrPut: create on first use

A very common pattern is "find the value for this key, and create it if it is not there yet". getOrPut does it in one step:

Kotlin getOrPut builds lists and caches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}, computing 4, 16 and 16. The lambda runs only when the key is missing, so the second square(4) does not print "computing". The same function with a cache map is the simplest form of memoization.

Iterating

Looping over a map gives you entries; destructure them into key and value:

Kotlin Looping over maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see the three name -> age lines, Ada Alan Grace , Ada:36 Alan:41 Grace:85 , Alan is over 40, Grace is over 40, [Ada(36), Alan(41), Grace(85)], 162 and Grace. Each entry is a Map.Entry with key and value. In lambdas, { (name, age) -> ... } destructures the entry; the extra parentheses distinguish "one entry" from "two parameters". See Pairs, Triples and Destructuring.

Transforming and filtering

Maps have their own versions of filter and map, plus functions that touch only keys or only values:

Kotlin Map transformations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are {ana=82, cy=91}, {cy=91}, {di=47}, {ana=8, bo=5, cy=9, di=4}, {ANA=82, BO=55, CY=91, DI=47}, [(di, 47), (bo, 55), (ana, 82), (cy, 91)], [cy, ana, bo, di] and [ana, cy]. filter, mapValues and mapKeys return a new map; map { } on a map returns a list. To sort a map, sort its entries (you get a list of entries) or build a sorted map, e.g. scores.toSortedMap() for keys in order, or toList().sortedBy { ... }.toMap() to rebuild a map in the desired order, which works because toMap() keeps the iteration order of the input.

Counting and grouping

Two jobs make up most real-world map code. For counting, use groupingBy { }.eachCount(); for collecting related items, use groupBy:

Kotlin Counting and grouping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is {one=1, fish=4, two=1, red=1, blue=1}, true, {4=[tree, star], 3=[sky, sea], 5=[tiger]}, {t=[TREE, TIGER], s=[SKY, SEA, STAR]}, {tree=4, sky=3, sea=3, tiger=5, star=4} and {t=tiger, s=star}. Two maps with the same entries are equal regardless of order, which is why manual == counts is true. associateBy keeps only the last element for each key (so t=tiger, not tree); use groupBy when you need all of them. More of these functions live in Collection Transformations.

There is also the merge function, which is handy for counting without the ?: 0 trick:

Kotlin Merge and compute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is {a=6, b=5} and {a=12, b=5, c=100}. merge stores the given value if the key is new, and combines old and new with your lambda otherwise.

Which map implementation?

Created with Implementation Iteration order
mapOf, mutableMapOf, linkedMapOf LinkedHashMap insertion order
hashMapOf HashMap unspecified
sortedMapOf, toSortedMap() TreeMap keys sorted

The default is a good choice for nearly everything. Keys follow the same rules as set elements: use immutable types with sound equals and hashCode, such as strings, numbers, enums and data classes. A mutable key that changes after insertion makes the entry unreachable, as shown in Sets. A TreeMap also gives you firstKey(), headMap() and floorKey() for range queries.

Kotlin Sorted maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You see {10=a, 20=b, 30=c}, 10, 20, {10=a}, {30=c, 20=b, 10=a} and {a=1, b=2}. floorKey(25) is the greatest key that is <= 25.

HashMap internals: capacity, load factor and complexity

Behind hashMapOf and mutableMapOf is a Java HashMap: an array of buckets. To store a key, Kotlin computes key.hashCode(), uses it to pick a bucket and puts the entry there. Lookups do the same calculation and then compare keys in that one bucket with equals. That is why get, put and containsKey take O(1) time on average, independent of the map's size.

Two numbers control the array. The capacity is the current number of buckets (16 by default). The load factor (0.75 by default) says how full the table may get before it grows: when size > capacity * loadFactor, the map doubles its capacity and redistributes every entry (a rehash). Rehashing is the expensive step, so if you know roughly how many entries you will add, tell the map up front:

Kotlin
val map = HashMap<String, Int>(1_000)           // initial capacity
val tuned = HashMap<String, Int>(1_000, 0.9f)   // capacity and load factor
val copy = HashMap(existingMap)                 // copy constructor

With a bad hashCode (for example one that returns a constant) all keys land in the same bucket and the map degrades; recent Java versions turn long buckets into balanced trees, which limits the damage to O(log n) for comparable keys, but a good hash is still the cure.

Kotlin Bad hash codes slow a HashMap down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three maps give the same answers, which is the point: the hash only changes how long you wait. A single lookup calls hashCode once, whether the map has ten entries or ten thousand.

Here is how the three common implementations compare:

Map Order of iteration get / put Needs
HashMap none guaranteed O(1) average good hashCode and equals
LinkedHashMap insertion order (the Kotlin default) O(1) average, a little more memory good hashCode and equals
TreeMap sorted by key O(log n) keys that are Comparable or a Comparator

LinkedHashMap is a HashMap that also links its entries in a chain, which gives predictable iteration. TreeMap keeps a balanced tree instead of buckets, so it is slower per operation but gives you sorted keys and range queries. Choose by what you need: speed alone, a stable order, or a sorted order.

Default values with withDefault

When a missing key should logically mean zero or empty, withDefault wraps a map so getValue falls back to a computed value:

Kotlin withDefault

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 3, 0 and null. Only getValue uses the default; the square-bracket operator still returns null. That surprises many people, so prefer getOrDefault in everyday code and keep withDefault for property delegation to maps.

Pitfalls

  • Reading with [] gives a nullable type. Handle it with ?:, or use getValue when absence is a bug.
  • A read-only Map can still change if it is a view of a MutableMap; copy with toMap() when you hand it out.
  • Order assumptions. Use a linked or sorted map when the order of iteration matters.
  • Duplicate keys in mapOf. Later pairs replace earlier ones silently: mapOf("a" to 1, "a" to 2) is {a=2}.
  • Modifying while iterating. Adding or removing during a loop over the map throws ConcurrentModificationException; see Mutable Collections and Iterators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does mapOf("a" to 1)["b"] evaluate to?

    Square-bracket access returns null for a missing key; only getValue throws.
  2. 2. Which function returns the existing value or computes, stores and returns a new one?

    getOrPut(key) { ... } runs the lambda only when the key is absent and stores its result.
  3. 3. What type does scores.map { (name, score) -> name } return for a Map<String, Int>?

    map on a map produces a list of the lambda results. Use mapValues or mapKeys to get a map back.
  4. 4. What does groupingBy { it }.eachCount() give you for a list of words?

    groupingBy with eachCount counts the occurrences of each key and returns a Map<K, Int>.
  5. 5. Which map iterates its keys in sorted order?

    sortedMapOf (a TreeMap) orders keys. mapOf and linkedMapOf keep insertion order, hashMapOf has none.

Summary

  • A map associates unique keys with values; create it with mapOf(k to v, ...) or mutableMapOf.
  • map[key] returns null for a missing key; getValue throws NoSuchElementException; getOrDefault, getOrElse and ?: supply fallbacks.
  • Assign with map[key] = value, and use getOrPut, merge and compute for create-or-update logic.
  • Loop with for ((key, value) in map); filter, mapValues and mapKeys return maps, map returns a list.
  • Count with groupingBy { }.eachCount() and collect with groupBy.
  • mapOf keeps insertion order, hashMapOf does not, sortedMapOf sorts by key; keep keys immutable.

Next: Arrays