How to get the current index in for each Kotlin

AndroidFor LoopKotlin

Android Problem Overview


How to get the index in a for each loop? I want to print numbers for every second iteration

For example

for (value in collection) {
    if (iteration_no % 2) {
        //do something
    }
}

In java, we have the traditional for loop

for (int i = 0; i < collection.length; i++)

How to get the i?

Android Solutions


Solution 1 - Android

In addition to the solutions provided by @Audi, there's also forEachIndexed:

collection.forEachIndexed { index, element ->
    // ...
}

Solution 2 - Android

Use indices

for (i in array.indices) {
    print(array[i])
}

If you want value as well as index Use withIndex()

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

Reference: Control-flow in kotlin

Solution 3 - Android

Alternatively, you can use the withIndex library function:

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

> Control Flow: if, when, for, while: > https://kotlinlang.org/docs/reference/control-flow.html

Solution 4 - Android

try this; for loop

for ((i, item) in arrayList.withIndex()) { }

Solution 5 - Android

Working Example of forEachIndexed in Android

Iterate with Index

itemList.forEachIndexed{index, item -> 
println("index = $index, item = $item ")
}

Update List using Index

itemList.forEachIndexed{ index, item -> item.isSelected= position==index}

Solution 6 - Android

It seems that what you are really looking for is filterIndexed

For example:

listOf("a", "b", "c", "d")
    .filterIndexed { index, _ ->  index % 2 != 0 }
    .forEach { println(it) }

Result:

b
d

Solution 7 - Android

Ranges also lead to readable code in such situations:

(0 until collection.size step 2)
    .map(collection::get)
    .forEach(::println)

Solution 8 - Android

Please try this once.

yourList?.forEachIndexed { index, data ->
     Log.d("TAG", "getIndex = " + index + "    " + data);
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdolf DsilvaView Question on Stackoverflow
Solution 1 - Androidzsmb13View Answer on Stackoverflow
Solution 2 - AndroidAdolf DsilvaView Answer on Stackoverflow
Solution 3 - AndroidAnoop M MaddasseriView Answer on Stackoverflow
Solution 4 - AndroidAli OzkaraView Answer on Stackoverflow
Solution 5 - AndroidHitesh SahuView Answer on Stackoverflow
Solution 6 - AndroidAkavallView Answer on Stackoverflow
Solution 7 - Androids1m0nw1View Answer on Stackoverflow
Solution 8 - AndroidSurendar DView Answer on Stackoverflow