0
0
KotlinHow-ToBeginner · 3 min read

How to Iterate Over Map in Kotlin: Syntax and Examples

In Kotlin, you can iterate over a map using for loops with map.entries to access key-value pairs, or use map.keys and map.values to iterate over keys or values separately. The for ((key, value) in map) syntax is a concise way to loop through each entry.
📐

Syntax

To iterate over a map in Kotlin, you typically use a for loop with one of these forms:

  • for ((key, value) in map) — loops over each key-value pair.
  • for (key in map.keys) — loops over all keys.
  • for (value in map.values) — loops over all values.

The map.entries property gives you access to each Map.Entry object containing a key and value.

kotlin
for ((key, value) in map) {
    // use key and value
}

for (key in map.keys) {
    // use key
}

for (value in map.values) {
    // use value
}
💻

Example

This example shows how to iterate over a map to print each key and its corresponding value using the for ((key, value) in map) syntax.

kotlin
fun main() {
    val map = mapOf("apple" to 3, "banana" to 5, "orange" to 2)

    for ((key, value) in map) {
        println("$key -> $value")
    }
}
Output
apple -> 3 banana -> 5 orange -> 2
⚠️

Common Pitfalls

One common mistake is trying to iterate over a map without destructuring the entry, like for (entry in map) and then trying to access entry.key and entry.value without destructuring. Another is modifying the map while iterating, which can cause errors.

Correct way uses destructuring:

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

// Wrong way (won't compile):
// for (entry in map) {
//     println(entry.key + ":" + entry.value)
// }

// Right way:
for ((key, value) in map) {
    println("$key:$value")
}
Output
a:1 b:2
📊

Quick Reference

Iteration MethodDescriptionExample Syntax
EntriesIterate over key-value pairsfor ((key, value) in map) { ... }
KeysIterate over keys onlyfor (key in map.keys) { ... }
ValuesIterate over values onlyfor (value in map.values) { ... }

Key Takeaways

Use for ((key, value) in map) to iterate over key-value pairs easily.
You can iterate keys or values separately with map.keys and map.values.
Avoid modifying a map while iterating to prevent errors.
Destructure map entries to access keys and values clearly.
Kotlin's concise syntax makes map iteration simple and readable.