How to iterate over a Map in Kotlin (for loop)

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

Solution: Here’s an example of how to iterate over a Map in Kotlin 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")
}

Inside that for loop the variables k and v refer to the Map keys and values, respectively.

Example in the Kotlin REPL

Here’s what this 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.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.