Get Current Index of for each Loop in Kotlin

Kotlin provides some ways to get the current index of any for each loop.

forEachIndexed performs the given action on each element, providing a sequential index with the element.

list.forEachIndexed { index, element ->
    Log.e("VALUE_OF_$index", element.toString())
}

indices returns the range of valid indices for the array.

for (i in list.indices) {
    Log.e("VALUE", list[i].toString())
}

withIndex returns a lazy Iterable that wraps each element of the original array/collection into an IndexedValue containing the index of that element and the element itself.

for ((index, element) in list.withIndex()) {
     Log.e("VALUE_OF_$index", element.toString())
}

filterIndexed can be used if users want to filter indices’ conditions.

listOf("Kotlin", "Java", "JavaScript", "C#")
    .filterIndexed { index, _ ->  index % 2 != 0 }
    .forEach { Log.e("VALUE", it) }

In the above example, it only logs “Java” and “C#”.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top