Iterate over a map in Kotlin
This article explores different ways to iterate over a map in Kotlin.
1. Using foreach Loop
A simple solution is to use a foreach loop for iteration through collections. You can iterate a map using the entries property, which returns a set of key/value pairs in the map.
|
1 2 3 4 5 |
fun <K, V> printMap(map: Map<K, V>) { for ((key, value) in map.entries) { println("${key}=$value") } } |
This approach will even work directly on map:
|
1 2 3 4 5 |
fun <K, V> printMap(map: Map<K, V>) { for ((key, value) in map) { println("${key}=$value") } } |
You can also iterate a map using the keys property, which returns a collection of the keys contained in the map.
|
1 2 3 4 5 |
private fun <K, V> printMap(map: Map<K, V>) { for (key in map.keys) { println("${key}=${map[key]}") } } |
2. Using forEach() function
You can also iterate a map with the forEach() function that performs an action for each mapping of the map.
|
1 2 3 |
fun <K, V> printMap(map: Map<K, V>) { map.forEach { println(it) } } |
You can also call forEach on keys returned by the keys property.
|
1 2 3 |
fun <K, V> printMap(map: Map<K, V>) { map.keys.forEach { println("${it}=${map[it]}") } } |
3. Using Iterator
You can easily process each key/value pair by getting an iterator to the map.
|
1 2 3 4 5 6 |
fun <K, V> printMap(map: Map<K, V>) { val itr = map.iterator() while (itr.hasNext()) { println(itr.next()) } } |
This can be shortened with the forEachRemaining() function, which performs the given action for each remaining element until all elements have been processed:
|
1 2 3 |
private fun <K, V> printMap(map: Map<K, V>) { map.iterator().forEachRemaining { println(it) } } |
Here’s an alternative solution that processes each key:
|
1 2 3 4 5 6 7 8 9 |
private fun <K, V> printMap(map: Map<K, V>) { val itr = map.keys.iterator() while (itr.hasNext()) { val key = itr.next() val value = map[key] println("${key}=$value") } } |
4. String Representation
Finally, if you just need to display all key/value pairs present on the map, you can print a string representation of the map.
|
1 2 3 4 5 |
fun main() { val map: Map<Int, String> = mapOf(1 to "A", 2 to "B", 3 to "C") println(map) // {1=A, 2=B, 3=C} } |
That’s all about iterating over a map in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)