如何获取每个Kotlin的当前索引

Aud*_*udi 100 android for-loop kotlin

如何为每个循环获取a的索引...我想每隔一次迭代打印数字

例如

for(value in collection) {
     if(iteration_no % 2) {
         //do something
     }
}
Run Code Online (Sandbox Code Playgroud)

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

for(int i=0; i< collection.length; i++)
Run Code Online (Sandbox Code Playgroud)

怎么弄到我?

zsm*_*b13 222

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

collection.forEachIndexed { index, element ->
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 哇,我觉得这个更好...谢谢 (3认同)

Aud*_*udi 75

使用 indices

for (i in array.indices) {
    print(array[i])
}
Run Code Online (Sandbox Code Playgroud)

如果你想要价值以及索引使用 withIndex()

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}
Run Code Online (Sandbox Code Playgroud)

参考:kotlin中的控制流

  • 我认为这个答案更好,因为不需要学习其他东西,只需简单的 for 循环 +1 (4认同)
  • 谢谢老兄,这真的很有帮助+1 (2认同)

Hit*_*ahu 40

Working Example of forEachIndexed in Android

Iterate with Index

itemList.forEachIndexed{index, item -> 
println("index = $index, item = $item ")
}
Run Code Online (Sandbox Code Playgroud)

Update List using Index

itemList.forEachIndexed{ index, item -> item.isSelected= position==index}
Run Code Online (Sandbox Code Playgroud)


Ano*_*p M 26

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

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}
Run Code Online (Sandbox Code Playgroud)

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


Sur*_*r D 13

请尝试一次。

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


ali*_*ara 11

尝试这个; for循环

for ((i, item) in arrayList.withIndex()) { }
Run Code Online (Sandbox Code Playgroud)

  • 尽管此代码可以回答问题,但提供有关如何和/或为什么解决问题的其他上下文将提高​​答案的长期价值。 (4认同)

Aka*_*all 8

看来你真正想要的是 filterIndexed

例如:

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

结果:

b
d
Run Code Online (Sandbox Code Playgroud)


s1m*_*nw1 5

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

(0 until collection.size step 2)
    .map(collection::get)
    .forEach(::println)
Run Code Online (Sandbox Code Playgroud)

  • 或者`(0..collection.lastIndex step 2)` (5认同)