Kotlin Maps: How to iterate over a Map in Kotlin with a 'for' loop

Kotlin FAQ: How do I iterate over the elements in a Map in Kotlin?

Solution

Here’s an example that shows how to iterate over the elements in a Kotlin Map using a for loop:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

for ((k,v) in map) {
    println("value of $k is $v")
}

In the first step of that example I create a Kotlin Map, and then in the second step — inside the Kotlin for loop — the variables k and v refer to the map’s keys and values, respectively.

Kotlin REPL example

Here’s what this Map/for solution looks like in the Kotlin REPL:

>>> val map = mapOf("a" to 1, "b" to 2, "c" to 3)

>>> for ((k,v) in map) {
...     println("value of $k is $v")
... }
value of a is 1
value of b is 2
value of c is 3

I hope this example of how to iterate over a Map in Kotlin using a for loop is helpful.