Get Current Index of for each Loop in Kotlin

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

forEachIndexed performs the given action on each element, providing 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 *

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. 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