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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close