How to Iterate Over Map in Kotlin: Simple Examples
To iterate over a
Map in Kotlin, use a for loop with destructuring syntax like for ((key, value) in map). You can also iterate over map.keys or map.values separately depending on your needs.Syntax
Use a for loop with destructuring to get both key and value from the map entries.
key: the map keyvalue: the map value
Alternatively, iterate over map.keys or map.values to get only keys or values.
kotlin
for ((key, value) in map) { // use key and value } // Or iterate keys only for (key in map.keys) { // use key } // Or iterate values only for (value in map.values) { // use value }
Example
This example shows how to iterate over a map and print each key and value pair.
kotlin
fun main() {
val map = mapOf("apple" to 3, "banana" to 5, "orange" to 2)
for ((key, value) in map) {
println("Key: $key, Value: $value")
}
}Output
Key: apple, Value: 3
Key: banana, Value: 5
Key: orange, Value: 2
Common Pitfalls
A common mistake is to iterate over map without destructuring, which gives Map.Entry objects that need explicit access to key and value.
Also, trying to modify a map while iterating over it can cause errors.
kotlin
fun main() {
val map = mapOf("a" to 1, "b" to 2)
// Iterating without destructuring and printing using entry.key and entry.value
for (entry in map) {
// entry is Map.Entry, so use entry.key and entry.value
println("Key: ${entry.key}, Value: ${entry.value}")
}
// Using destructuring
for ((key, value) in map) {
println("Key: $key, Value: $value")
}
}Output
Key: a, Value: 1
Key: b, Value: 2
Key: a, Value: 1
Key: b, Value: 2
Quick Reference
Here is a quick summary of ways to iterate over a Kotlin map:
| Method | Description | Example |
|---|---|---|
| Destructuring in for loop | Get key and value together | for ((k,v) in map) { ... } |
| Iterate keys | Get only keys | for (k in map.keys) { ... } |
| Iterate values | Get only values | for (v in map.values) { ... } |
| Iterate entries | Use Map.Entry objects | for (entry in map) { entry.key, entry.value } |
Key Takeaways
Use for ((key, value) in map) to iterate over keys and values together.
You can iterate keys or values separately using map.keys or map.values.
Map entries can be accessed as Map.Entry objects if not destructured.
Avoid modifying a map while iterating over it to prevent errors.
Destructuring makes code cleaner and easier to read when iterating maps.