Authors Top

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this short tutorial, we’ll look at how to iterate over a map in Kotlin. We’ll see how we can do this with for loops, iterators, and some handy extension functions.

2. Iterate With a for Loop

The simplest way to iterate over a map is to iterate over its Entry objects:

val map = mapOf("Key1" to "Value1", "Key2" to "Value2", "Key3" to "Value3")
map.forEach { entry ->
    print("${entry.key} : ${entry.value}")
}

Here, the in operator gives us a handle to the iterator of the map’s entries property. This is essentially the same as:

for (entry in map.entries.iterator()) {
    print("${entry.key} : ${entry.value}")
}

3. Using forEach 

We can also use the handy forEach extension function:

map.forEach { entry ->
    print("${entry.key} : ${entry.value}")
}

To further reduce boilerplate, we can use destructuring. Doing so expands the Entry into handy key and value variables:

map.forEach { (key, value) ->
    print("$key : $value")
}

4. Using the Map.keys Property

Sometimes, we’d only like to iterate over the keys in the map. In that case, we can use the map’s keys property:

for (key in map.keys) {
    print(key)
}

Here, we get a Set of all keys in the map. This also means we can use the Set‘s forEach extension function:

map.keys.forEach { key ->
    val value = map[key]
    print("$key : $value")
}

We should note that iterating over keys and values this way is less efficient. This is because we make multiple get calls on the map to fetch values for the given keys. This can be avoided by using the Entry iteration approach, for instance.

5. Using the map.values Property

Similarly, we can use the map’s values property to get a collection of all values:

for (value in map.values) {
    print(value)
}

Since the values property gives us a collection, we can use the forEach pattern here:

map.values.forEach { value ->
    print(value)
}

6. Conclusion

In this article, we saw several ways to iterate over a map. Some approaches are more flexible but come with a performance cost.

For most use cases, using forEach over entries is a good option.

As always, the code samples are available over on GitHub.

Authors Bottom

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!