The syntax of Map.onEach() extension function is:
fun <K, V, M : Map<out K, V>> M.onEach( action: (Entry<K, V>) -> Unit ): M
This onEach() extension function of Map performs the given action on each entry and returns the map itself afterwards.
In this example,
map1
containing key-value pairs 1 to 'a'
, 2 to 'b'
, and 3 to 'c'
.onEach()
function on map1
to perform an action on each entry, in this case, printing the key and value.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}") }
}
Key: 1, Value: a Key: 2, Value: b Key: 3, Value: c
In this example,
map2
containing key-value pairs 'a' to 1
, 'b' to 2
, and 'c' to 3
.onEach()
function on map2
to perform an action on each entry, in this case, printing the key and value.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}") }
}
Key: a, Value: 1 Key: b, Value: 2 Key: c, Value: 3
In this example,
map3
containing key-value pairs 1 to "apple"
, 2 to "banana"
, and 3 to "cherry"
.onEach()
function on map3
to perform an action on each entry, in this case, printing the key and value.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}") }
}
Key: 1, Value: apple Key: 2, Value: banana Key: 3, Value: cherry
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.