1
fun forLoopListItems() {
        val items = listOf("apple", "banana", "kiwifruit")
        for (i in items) {
            if (i.equals("banana")) {
              println("position is ${i.indices}")
            }
        }
    }

This is My Kotlin code used with For Loop. I tried to Print Index Curresponding to "banana" But Result is "System.out: position is 0..5" How is it Become 0..5 ?

Muhammed Haris
  • 340
  • 1
  • 5
  • 15
  • 2
    Possible duplicate of [How to get the current index in for each Kotlin](https://stackoverflow.com/questions/48898102/how-to-get-the-current-index-in-for-each-kotlin) – Shahab Rauf Apr 02 '18 at 09:11

3 Answers3

4

The indices method gives you a range, which is 0..5 in this case because it's called on the String: banana with a length of 6.

You can instead iterate with indices as follows:

items.forEachIndexed { i, element ->
    if (element == "banana") {
        println("position is $i")
    }
}

Alternative ways of iterating with indices are listed in this post.

I'm not sure if you really want to iterate explicitly though. Maybe it's fine for you to use built-in functions for finding the index of your element:

println(items.indexOf("banana"))
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
1

There is indexOf:

Returns first index of element, or -1 if the collection does not contain element.

and lastIndexOf:

Returns last index of element, or -1 if the collection does not contain element.

val items = listOf("apple", "banana", "kiwifruit")
val appleIndex = items.indexOf("apple") // 0
val lastAppleIndex = items.lastIndexOf("apple") // 0
val bananaIndex = items.indexOf("banana")  // 1
val orangeIndex = items.indexOf("orange")  // -1
miensol
  • 39,733
  • 7
  • 116
  • 112
0

You can iterate with Index using forEachIndexed method of Kotlin

Iterate with Index

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

Check if item is Banana and print Index

itemList.forEachIndexed{ index, item -> {
         if (item.equals("banana")) {println("position is ${index}")}
              }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154