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.

 
This approach will even work directly on map:

 
You can also iterate a map using the keys property, which returns a collection of the keys contained in the map.

2. Using forEach() function

You can also iterate a map with the forEach() function that performs an action for each mapping of the map.

 
You can also call forEach on keys returned by the keys property.

3. Using Iterator

You can easily process each key/value pair by getting an iterator to the map.

 
This can be shortened with the forEachRemaining() function, which performs the given action for each remaining element until all elements have been processed:

 
Here’s an alternative solution that processes each key:

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.

Download Code

That’s all about iterating over a map in Kotlin.