如何获得索引在一个为每个循环?我想每次迭代都打印数字

例如

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

在java中,我们有传统的for循环

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

如何得到i?


使用索引

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

如果你想要值和索引,使用withIndex()

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

参考:kotlin中的Control-flow

除了@Audi提供的解决方案,还有forEachIndexed:

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

似乎您真正要找的是filterIndexed

例如:

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

结果:

b
d

在这种情况下,范围也会导致可读的代码:

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

试试这个;for循环

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

或者,你可以使用withIndex库函数:

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

控制流:if, when, for, while: https://kotlinlang.org/docs/reference/control-flow.html

Android中forEachIndexed的工作示例

用索引迭代

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

使用索引更新列表

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

请试一次。

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

你可以初始化一个变量counter=0并在循环中增加:

for (value in collection){//do something then count++ }`