Adolf Dsilva
Adolf Dsilva

Reputation: 14390

How to get the current index in for each Kotlin

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 % 2) {
        //do something
    }
}

In java, we have the traditional for loop

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

How to get the i?

Upvotes: 402

Views: 305262

Answers (10)

devu mani
devu mani

Reputation: 377

we can also write for loop like this

fun main() {
    val array = arrayOf(3, 9, 6, 9, 3, 9)
    for (i in 0 until array.size) {
        println("Index: $i, Value: ${array[i]}")
    }
}

Upvotes: 1

user19459910
user19459910

Reputation: 1

You can initialize a variable counter=0 and increment inside the loop:

for (value in collection){//do something then count++ }`

Upvotes: 0

Surendar D
Surendar D

Reputation: 5644

Please try this once.

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

Upvotes: 16

Hitesh Sahu
Hitesh Sahu

Reputation: 45140

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}

Upvotes: 42

Anoop M Maddasseri
Anoop M Maddasseri

Reputation: 10559

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

Upvotes: 82

ali ozkara
ali ozkara

Reputation: 5646

try this; for loop

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

Upvotes: 42

Akavall
Akavall

Reputation: 86306

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

Upvotes: 15

s1m0nw1
s1m0nw1

Reputation: 82047

Ranges also lead to readable code in such situations:

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

Upvotes: 8

zsmb13
zsmb13

Reputation: 89628

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

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

Upvotes: 714

Adolf Dsilva
Adolf Dsilva

Reputation: 14390

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

Upvotes: 265

Related Questions