Kotlin Map onEach()
Syntax & Examples
Syntax of Map.onEach()
The syntax of Map.onEach() extension function is:
fun <K, V, M : Map<out K, V>> M.onEach( action: (Entry<K, V>) -> Unit ): MThis onEach() extension function of Map performs the given action on each entry and returns the map itself afterwards.
✐ Examples
1 Print each entry in the map
In this example,
- We create a map named
map1containing key-value pairs1 to 'a',2 to 'b', and3 to 'c'. - We then apply the
onEach()function onmap1to perform an action on each entry, in this case, printing the key and value. - The function returns the map itself.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
map1.onEach { entry -> println("Key: ${entry.key}, Value: ${entry.value}") }
}Output
Key: 1, Value: a Key: 2, Value: b Key: 3, Value: c
2 Print each entry in the map
In this example,
- We create a map named
map2containing key-value pairs'a' to 1,'b' to 2, and'c' to 3. - We then apply the
onEach()function onmap2to perform an action on each entry, in this case, printing the key and value. - The function returns the map itself.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3);
map2.onEach { entry -> println("Key: ${entry.key}, Value: ${entry.value}") }
}Output
Key: a, Value: 1 Key: b, Value: 2 Key: c, Value: 3
3 Print each entry in the map
In this example,
- We create a map named
map3containing key-value pairs1 to "apple",2 to "banana", and3 to "cherry". - We then apply the
onEach()function onmap3to perform an action on each entry, in this case, printing the key and value. - The function returns the map itself.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry");
map3.onEach { entry -> println("Key: ${entry.key}, Value: ${entry.value}") }
}Output
Key: 1, Value: apple Key: 2, Value: banana Key: 3, Value: cherry
Summary
In this Kotlin tutorial, we learned about onEach() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.