The syntax of Map.onEachIndexed() extension function is:
fun <K, V, M : Map<out K, V>> M.onEachIndexed( action: (index: Int, Entry<K, V>) -> Unit ): M
This onEachIndexed() extension function of Map performs the given action on each entry, providing sequential index with the 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'
.onEachIndexed()
function on map1
to perform an action on each entry with its sequential index, in this case, printing the index, key, and value.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
map1.onEachIndexed { index, entry -> println("Index: $index, Key: ${entry.key}, Value: ${entry.value}") }
}
Index: 0, Key: 1, Value: a Index: 1, Key: 2, Value: b Index: 2, Key: 3, Value: c
In this example,
map2
containing key-value pairs 'a' to 1
, 'b' to 2
, and 'c' to 3
.onEachIndexed()
function on map2
to perform an action on each entry with its sequential index, in this case, printing the index, key, and value.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3);
map2.onEachIndexed { index, entry -> println("Index: $index, Key: ${entry.key}, Value: ${entry.value}") }
}
Index: 0, Key: a, Value: 1 Index: 1, Key: b, Value: 2 Index: 2, Key: c, Value: 3
In this example,
map3
containing key-value pairs 1 to "apple"
, 2 to "banana"
, and 3 to "cherry"
.onEachIndexed()
function on map3
to perform an action on each entry with its sequential index, in this case, printing the index, key, and value.fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry");
map3.onEachIndexed { index, entry -> println("Index: $index, Key: ${entry.key}, Value: ${entry.value}") }
}
Index: 0, Key: 1, Value: apple Index: 1, Key: 2, Value: banana Index: 2, Key: 3, Value: cherry
In this Kotlin tutorial, we learned about onEachIndexed() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.