How to get the current index in for each Kotlin

2019-01-23 10:57发布

问题:

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

For example

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

In java we have the traditional for loop

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

How to get the i?

回答1:

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

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


回答2:

Use indices

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

If you want value as well as index Use withIndex()

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

Reference: Control-flow in kotlin



回答3:

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


回答4:

try this; for loop

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


回答5:

Ranges also lead to readable code in such situations:

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


回答6:

You can use :

for(i in 0..collection.length) {
     if(collection[i] % 2 == 0) {
         //do something
     }
}