如何在Kotlin的for each循环中获取当前索引

375
如何在for each循环中获取索引?我想在每两次迭代中打印数字。
例如:
for (value in collection) {
    if (iteration_no % 2) {
        //do something
    }
}

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

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

如何获取 i 变量?


1
请参考以下链接:https://dev59.com/tVYN5IYBdhLWcg3w1LIG#46826172。 - s1m0nw1
9个回答

672

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

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

1
它适用于数组和可迭代对象,你还需要它适用于什么? - zsmb13
1
抱歉,我对Java原始数组感到困惑。 - Adolf Dsilva
1
有没有办法在 <% %> 里使用 break - Levon Petrosyan
1
你不能从整个循环中跳出,唯一类似的操作是使用 return@forEachIndexed,它本质上相当于 continue 跳过当前元素。如果你需要跳出循环,你必须将其包装在一个函数中,并在循环中使用 return 从该封闭函数中返回。 - zsmb13
使用这个将会防止你使用 continue,如果你需要这样的功能,请使用 @Audi 的答案。 - Mihae Kheel
每个循环和for循环之间有性能差异吗? - Bolt UIX

234

使用indices

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

如果你想同时获取值和索引,使用withIndex()

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

参考: Kotlin中的控制流程


7
我会尽力进行翻译:我认为这个答案更好,因为它不需要学习其他东西,只需要使用简单的for循环+1。 - underfilho

72

41

试试这个; for循环

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

8
虽然这段代码可以回答问题,但提供关于它如何以及/或者为什么解决问题的额外背景信息会增加答案的长期价值。 - Reinstate Monica
我该如何为这个循环设置限制?比如说让它一直执行到一半或者在结束前的某些数字停止。 - E.Akio
@E.Akio 一个选项是使用子列表:arrayList.subList(0, arrayList.size/2) - Dario Seidl

39

在Android中使用forEachIndexed的实际示例

带索引迭代

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

使用索引更新列表

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

13

请尝试执行一次。

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

13

看起来你真正需要的是filterIndexed

例如:

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

结果:

b
d

1
请考虑使用函数引用.forEach(::println) - Kirill Rakhman
@KirillRakhman,在这种情况下使用函数引用是首选的风格吗?我是 Kotlin 的新手,所以我还在摸索这些东西。 - Akavall
我倾向于尽可能使用函数引用。当你有多个参数时,与使用lambda相比,你可以节省很多字符。但这肯定是一个品味问题。 - Kirill Rakhman

7

范围 在这种情况下还可以导致可读性更强的代码:

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

5
替代的方式是 (0..collection.lastIndex step 2),意思是从0开始到collection中最后一个元素的索引,每隔两个数取一个。 - Kirill Rakhman

0
你可以初始化一个变量 counter=0 并在循环内进行增量操作:
for (value in collection){//do something then count++ }`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接