Kotlin Map onEachIndexed()
Syntax & Examples
Syntax of Map.onEachIndexed()
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 ): MThis onEachIndexed() extension function of Map performs the given action on each entry, providing sequential index with the entry, and returns the map itself afterwards.
✐ Examples
1 Print each entry with index 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 onEachIndexed()function onmap1to perform an action on each entry with its sequential index, in this case, printing the index, 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.onEachIndexed { index, entry -> println("Index: $index, Key: ${entry.key}, Value: ${entry.value}") }
}Output
Index: 0, Key: 1, Value: a Index: 1, Key: 2, Value: b Index: 2, Key: 3, Value: c
2 Print each entry with index 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 onEachIndexed()function onmap2to perform an action on each entry with its sequential index, in this case, printing the index, 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.onEachIndexed { index, entry -> println("Index: $index, Key: ${entry.key}, Value: ${entry.value}") }
}Output
Index: 0, Key: a, Value: 1 Index: 1, Key: b, Value: 2 Index: 2, Key: c, Value: 3
3 Print each entry with index 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 onEachIndexed()function onmap3to perform an action on each entry with its sequential index, in this case, printing the index, 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.onEachIndexed { index, entry -> println("Index: $index, Key: ${entry.key}, Value: ${entry.value}") }
}Output
Index: 0, Key: 1, Value: apple Index: 1, Key: 2, Value: banana Index: 2, Key: 3, Value: cherry
Summary
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.
