This article explores different ways to apply a function to each entry of a Map in Kotlin.

1. Using replaceAll() function

To apply a function to each entry of a Map in Kotlin, you can use the replaceAll() function that replaces each entry’s value with the result of invoking the given function on that entry. For example, the following solution applies the toUpperCase() function to each value in the map.

Download Code

Output:

{1=one, 2=two, 3=three}

 
The replaceAll() function invokes the given function on each entry’s value until all entries have been processed, or the function throws an exception. For instance, the above code will throw an exception for a null value in the map. This can be handled as follows:

Download Code

Output:

{1=one, 2=two, 3=null}

2. Using Loop

Alternatively, you can use replace the replaceAll() function with a simple for loop. The for-loop iterates through anything that has an iterator. So, you can loop over the MutableSet of all key/value pairs in this map, as shown below:

Download Code

Output:

{1=one, 2=two, 3=three}

That’s all about applying a function to each entry of a Map in Kotlin.