Multiple ways to iterate Map in Kotlin with example
Map is a data structure that contains key-value pairs.
This tutorial explains multiple ways to iterate through a Map in Kotlin with examples.
Multiple ways to iterate Key and value pair in Kotlin
There are multiple ways to iterate through key-value pairs in Kotlin.
- use for in loop
In this approach, the for-in loop is used to iterate through each object in the map, where each object represents a key-value pair. The key and value pairs are printed using the $variable syntax.
fun main() {
    val map = HashMap<String, String>();
    map["1"] = "one"
    map["2"] = "two"
    map["3"] = "three"
    map["4"] = "four"
    map["5"] = "five"
    for ((key, value) in map) {
        println("$key - $value")
    }
}
Output:
1 - one
2 - two
3 - three
4 - four
5 - five
- use forEach loop
The map contains a forEach function that iterates through the map with a callback. The callback contains the key and value, which are then printed.
Here is an example
fun main() {
    val map = HashMap<String, String>()
    map["1"] = "one"
    map["2"] = "two"
    map["3"] = "three"
    map["4"] = "four"
    map["5"] = "five"
    map.forEach { (key, value) ->
        println("$key = $value")
    }
}
- use Iterator function
The Map.keys function returns an array of keys, which is then used with an iterator. The iterator checks if there are elements to iterate using iterator.hasNext(), and iterator.next() returns the next element in the array. The value for a key is retrieved using the Map[key] function.
Here is an example
fun main() {
    val map = HashMap<String, String>()
    map["1"] = "one"
    map["2"] = "two"
    map["3"] = "three"
    map["4"] = "four"
    map["5"] = "five"
    val iterator = map.keys.iterator()
    while (iterator.hasNext()) {
        val key = iterator.next()
        val value = map[key]
        println("$key - $value")
    }
}
Output:
1 - one
2 - two
3 - three
4 - four
5 - five
Conclusion
These are different approaches you can use to iterate through key-value pairs in a Kotlin Map, providing flexibility based on your need.
