【问题标题】:How to get the current index in for each Kotlin如何获取每个 Kotlin 的当前索引
【发布时间】:2023-03-05 02:54:01
【问题描述】:

如何在 for each 循环中获取索引?我想为每第二次迭代打印一次数字

例如

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

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

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

如何获取i

【问题讨论】:

标签: android for-loop kotlin


【解决方案1】:

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

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

【讨论】:

  • 它适用于 Arrays 和 Iterables,你还需要它来做什么?
  • 很抱歉与原始 java 数组混淆。
  • 有什么方法可以在里面使用break
  • 你不能从整个循环中中断,你唯一能做的类似的事情是return@forEachIndexed,它本质上将作为continue跳到下一个元素。如果需要中断,则必须将其包装在一个函数中,并在循环中使用return 从该封闭函数返回。
  • 使用这个会阻止你使用continue如果你需要这样的功能使用@Audi回答
【解决方案2】:

使用indices

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

如果您想要价值和索引,请使用withIndex()

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

参考:Control-flow in kotlin

【讨论】:

  • 我认为这个答案更好,因为不需要学习其他东西,只需简单的 for 循环 +1
【解决方案3】:

或者,您可以使用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

【讨论】:

    【解决方案4】:

    试试这个; for循环

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

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    • 如何限制这个循环?就像它一直持续到结束前的一半或一些数字
    • @E.Akio 一种选择是使用子列表:arrayList.subList(0, arrayList.size/2)
    【解决方案5】:

    forEachIndexed 在 Android 中的工作示例

    使用索引迭代

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

    使用索引更新列表

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

    【讨论】:

      【解决方案6】:

      看来你真正要找的是filterIndexed

      例如:

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

      结果:

      b
      d
      

      【讨论】:

      • 也可以考虑使用函数引用.forEach(::println)
      • @KirillRakhman,在这种情况下是否使用函数引用首选样式?我是 Kotlin 的新手,所以我还在搞清楚这些东西。
      • 我倾向于尽可能使用函数引用。当您有多个参数时,与使用 lambda 相比,您可以节省一堆字符。但这肯定是口味问题。
      【解决方案7】:

      Ranges 在这种情况下也会导致代码可读:

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

      【讨论】:

      • 或者(0..collection.lastIndex step 2)
      猜你喜欢
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2011-06-28
      相关资源
      最近更新 更多