How to get the current index in for each Kotlin

前端 未结 7 1283
Happy的楠姐
Happy的楠姐 2021-01-30 01:51

How to get the index in a for each loop? I want to print numbers for every second iteration

For example

for (value in collection) {
    if (iteration_no %          


        
相关标签:
7条回答
  • 2021-01-30 02:19

    try this; for loop

    for ((i, item) in arrayList.withIndex()) { }
    
    0 讨论(0)
  • 2021-01-30 02:21

    Ranges also lead to readable code in such situations:

    (0 until collection.size step 2)
        .map(collection::get)
        .forEach(::println)
    
    0 讨论(0)
  • 2021-01-30 02:30

    It seems that what you are really looking for is filterIndexed

    For example:

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

    Result:

    b
    d
    
    0 讨论(0)
  • 2021-01-30 02:35

    Working Example of forEachIndexed in Android

    Iterate with Index

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

    Update List using Index

    itemList.forEachIndexed{ index, item -> item.isSelected= position==index}
    
    0 讨论(0)
  • 2021-01-30 02:37

    Alternatively, you can use the withIndex library function:

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

    Control Flow: if, when, for, while: https://kotlinlang.org/docs/reference/control-flow.html

    0 讨论(0)
  • 2021-01-30 02:38

    In addition to the solutions provided by @Audi, there's also forEachIndexed:

    collection.forEachIndexed { index, element ->
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题