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 %
try this; for loop
for ((i, item) in arrayList.withIndex()) { }
Ranges also lead to readable code in such situations:
(0 until collection.size step 2)
.map(collection::get)
.forEach(::println)
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
forEachIndexed
in AndroidIterate with Index
itemList.forEachIndexed{index, item ->
println("index = $index, item = $item ")
}
Update List using Index
itemList.forEachIndexed{ index, item -> item.isSelected= position==index}
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
In addition to the solutions provided by @Audi, there's also forEachIndexed:
collection.forEachIndexed { index, element ->
// ...
}