Kotlin List forEachIndexed()
Syntax & Examples
Syntax of List.forEachIndexed()
The syntax of List.forEachIndexed() extension function is:
fun <T> Iterable<T>.forEachIndexed( action: (index: Int, T) -> Unit)
This forEachIndexed() extension function of List performs the given action on each element, providing sequential index with the element.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list1
. - We use the
forEachIndexed()
function onlist1
to print each element with its index to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5)
list1.forEachIndexed { index, value -> println("Index: \$index, Value: \$value") }
}
Output
Index: 0, Value: 1 Index: 1, Value: 2 Index: 2, Value: 3 Index: 3, Value: 4 Index: 4, Value: 5
2 Example
In this example,
- We create a list of characters named
list2
. - We use the
forEachIndexed()
function onlist2
to print each element with its index to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c')
list2.forEachIndexed { index, value -> println("Index: \$index, Value: \$value") }
}
Output
Index: 0, Value: a Index: 1, Value: b Index: 2, Value: c
3 Example
In this example,
- We create a list of strings named
list3
. - We use the
forEachIndexed()
function onlist3
to print each element with its index to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry")
list3.forEachIndexed { index, value -> println("Index: \$index, Value: \$value") }
}
Output
Index: 0, Value: apple Index: 1, Value: banana Index: 2, Value: cherry
Summary
In this Kotlin tutorial, we learned about forEachIndexed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.