How to get the current index in for each Kotlin
如何在每个循环中获取索引?我想为第二次迭代打印数字
例如
1 2 3 4 5 | for (value in collection) { if (iteration_no % 2) { //do something } } |
在Java中,我们具有传统的for循环
1 | for (int i = 0; i < collection.length; i++) |
如何获取
除了@Audi提供的解决方案之外,还有
1 2 3 | collection.forEachIndexed { index, element -> // ... } |
使用
1 2 3 | for (i in array.indices) { print(array[i]) } |
如果需要值和索引,请使用
1 2 3 | for ((index, value) in array.withIndex()) { println("the element at $index is $value") } |
参考:Kotlin中的控制流
尝试一下; for循环
1 | for ((i, item) in arrayList.withIndex()) { } |
或者,您可以使用
1 2 3 | 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
看来您真正要寻找的是
例如:
1 2 3 | listOf("a","b","c","d") .filterIndexed { index, _ -> index % 2 != 0 } .forEach { println(it) } |
结果:
1 2 | b d |
在这种情况下,范围也会导致可读代码:
1 2 3 | (0 until collection.size step 2) .map(collection::get) .forEach(::println) |
Android中
使用索引
进行迭代
1 2 3 | itemList.forEachIndexed{index, item -> println("index = $index, item = $item") } |
使用索引更新列表
1 | itemList.forEachIndexed{ index, item -> item.isSelected= position==index} |