如何获取每个循环的索引... 我想每隔一次迭代打印数字
例如
for(value in collection) {
if(iteration_no % 2) {
//do something
}
}
在java中,我们有传统的for循环
for(int i=0; i< collection.length; i++)
如何获得i?
答案 0 :(得分:149)
除了@Audi提供的解决方案之外,还有forEachIndexed
:
collection.forEachIndexed { index, element ->
// ...
}
答案 1 :(得分:45)
使用indices
for (i in array.indices) {
print(array[i])
}
如果您想要价值和索引使用withIndex()
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
答案 2 :(得分:8)
您真正想要的是filterIndexed
例如:
listOf("a", "b", "c", "d")
.filterIndexed { index, _ -> index % 2 != 0 }
.forEach { println(it) }
结果:
b
d
答案 3 :(得分:5)
尝试一下;循环
for ((i, item) in arrayList.withIndex()) { }
答案 4 :(得分:2)
Ranges也会导致可读代码:
(0 until collection.size step 2)
.map(collection::get)
.forEach(::println)
答案 5 :(得分:1)
或者,您可以使用withIndex
库函数:
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
答案 6 :(得分:0)
forEachIndexed
的工作示例迭代索引
itemList.forEachIndexed{index, item ->
println("index = $index, item = $item ")
}
使用索引更新列表
itemList.forEachIndexed{ index, item -> item.isSelected= position==index}
答案 7 :(得分:-1)
您可以使用:
for(i in 0..collection.length) {
if(collection[i] % 2 == 0) {
//do something
}
}