CodeBlanks Logo Icon CodeBlanks

Map iteration

Learn to iterate over maps with for.

Map iteration: walking with for

To walk all pairs of a map you use the for ((k, v) in map) loop. Here k is the key and v is the value. To walk only keys or only values you use map.keys or map.values.

val ages = mapOf("Ava" to 25, "Liam" to 30)
for ((name, age) in ages) {
    println("$name: $age")
}

This destructuring loop splits each Entry into its key and value components automatically.

forEach and the Entry type

forEach { } walks each pair with a lambda. Inside the lambda the element is an Entry<K, V>; you reach its parts with .key and .value.

ages.forEach { entry ->
    println("${entry.key} = ${entry.value}")
}
// or the short form:
ages.forEach { println("${it.key} = ${it.value}") }

it is the automatic name of the single lambda parameter; that is why naming is optional for one-parameter lambdas.

Practice Print city-population pairs

Create a mapOf("Vienna" to 1, "Berlin" to 3). Use a for ((city, pop) in pops) loop to print each pair as "$city: $pop million" on its own line.

Starter code

Main.kt
fun main() {
    val pops = mapOf("Vienna" to 1, "Berlin" to 3)
    // Print each city-population pair as "city: pop million"
}

Sample solution

Main.kt
fun main() {
    val pops = mapOf("Vienna" to 1, "Berlin" to 3)
    for ((city, pop) in pops) {
        println("$city: $pop million")
    }
}

Expected output

Vienna: 1 million
Berlin: 3 million

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: map loop

Question
for ((k, v) ____ map) println("$k = $v")
Answer
for ((k, v) in map) println("$k = $v")

Explanation: for ((k, v) in map) walks each pair.

2 Match loop expression to use

Term Meaning
for ((k, v) in map) Walks key-value pairs
for (k in map.keys) Walks only keys
for (v in map.values) Walks only values
map.entries All Entry pairs

3 In for (x in map), what is the type of x?

  • Exception
  • Only the key
  • Only the value
  • Entry<K, V> Correct answer

Explanation: When you iterate a map with for, each element is an Entry<K, V>.

All lessons in Beginner