370

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?

iknow
  • 8,358
  • 12
  • 41
  • 68
Adolf Dsilva
  • 13,092
  • 8
  • 34
  • 45
  • 1
    also see https://stackoverflow.com/questions/46825787/does-kotlin-have-an-enumerate-function-like-python/46826172#46826172 – s1m0nw1 Feb 21 '18 at 08:04

9 Answers9

659

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

collection.forEachIndexed { index, element ->
    // ...
}
zsmb13
  • 85,752
  • 11
  • 221
  • 226
228

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

Adolf Dsilva
  • 13,092
  • 8
  • 34
  • 45
69

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

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
41

try this; for loop

for ((i, item) in arrayList.withIndex()) { }
ali ozkara
  • 5,425
  • 2
  • 27
  • 24
  • 8
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Reinstate Monica Oct 15 '18 at 18:04
  • How can i put a limit for this loop? Like it goes until half or some numbers before end – E.Akio Jul 17 '20 at 14:59
  • @E.Akio One option would be to work with a sub list: `arrayList.subList(0, arrayList.size/2)`. – Dario Seidl Nov 18 '21 at 14:48
37

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}
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
13

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
Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • 1
    also consider using a function reference `.forEach(::println)` – Kirill Rakhman Feb 26 '18 at 09:00
  • @KirillRakhman, is using function references preferred style in situations like that? I am new to Kotlin, so I am still figuring this stuff out. – Akavall Feb 26 '18 at 17:53
  • I tend to use function references whenever possible. When you have more than one parameter, you save a bunch of characters compared to using a lambda. But it's a matter of taste for sure. – Kirill Rakhman Feb 26 '18 at 21:13
10

Please try this once.

yourList?.forEachIndexed { index, data ->
     Log.d("TAG", "getIndex = " + index + "    " + data);
 }
Surendar D
  • 5,554
  • 4
  • 36
  • 38
7

Ranges also lead to readable code in such situations:

(0 until collection.size step 2)
    .map(collection::get)
    .forEach(::println)
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
0

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

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