Skip to main content

Get the Current Index of for each Loop in Kotlin

Kotlin provides a variety of tools for working with for each loops, enabling developers to easily iterate through collections and other data structures. One useful feature is the ability to get the current index of a loop iteration. This allows you to keep track of your position within a list or array, making it easier to process each item individually or perform complex calculations based on the current position.

There are several different functions that can be used for this purpose. Each of these functions handles slightly different cases, so it’s important to use the appropriate one in your code.

list.forEachIndexed { index, element ->
    Log.e("$index", element.toString())
}
for (i in list.indices) {
    Log.e("VALUE", list[i].toString())
}
for ((index, element) in list.withIndex()) {
     Log.e("$index", element.toString())
}
listOf("Samsung", "Huawei", "Apple", "Oppo")
    .filterIndexed { index, _ ->  index % 2 != 0 }
    .forEach { Log.e("VALUE", it) }

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