Apply a function to each entry of a Map in Kotlin
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.
|
1 2 3 4 5 |
fun main() { val map = mutableMapOf<Int, String>(Pair(1, "ONE"), Pair(2, "TWO"), Pair(3, "THREE")) map.replaceAll { _, value -> value.toLowerCase() } println(map) } |
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:
|
1 2 3 4 5 |
fun main() { val map = mutableMapOf<Int, String?>(Pair(1, "ONE"), Pair(2, "TWO"), Pair(3, null)) map.replaceAll { _, value -> value?.toLowerCase() } println(map) } |
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:
|
1 2 3 4 5 6 7 8 9 |
fun main() { val map = mutableMapOf<Int, String>(Pair(1, "ONE"), Pair(2, "TWO"), Pair(3, "THREE")) for (entry in map.entries) { val value = entry.value entry.setValue(value.toLowerCase()) } println(map) } |
Output:
{1=one, 2=two, 3=three}
That’s all about applying a function to each entry of 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 :)