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 ?

1

3 Answers 3

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"))
Sign up to request clarification or add additional context in comments.

1 Comment

usage of -> is find in Many Places ,,why its Used?
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

Comments

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}")}
              }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.