HI all - I would really appreciate some guidance o...
# getting-started
c
HI all - I would really appreciate some guidance on extracting values and/or indexes from a List. I'm working on some of the hyperskill courses and one question is returning the index of a given value - which may be duplicated- from a list. Given the following list:
Copy code
val products = listOf("milk", "eggs", "bread", "cheese", "eggs", "greens")
return the index(es) of a given string; e.g. "eggs" should return
1 4
. After some experimenting I've been trying to use forEachIndexed(), but I don't know how to express 'print $index where $value == "eggs"'. Can someone provide any pointers? Alternate approaches are welcome, of course 😄 Thanks in advance for your help!
Copy code
val products = listOf("milk", "eggs", "bread", "cheese", "eggs", "greens")
products.forEachIndexed { index, s -> println("${s} ${index}") }
products.forEachIndexed { index, s -> ??? }
h
I think you can use this approach.
Copy code
val products = listOf("milk", "eggs", "bread", "cheese", "eggs", "greens")
products.forEachIndexed {  index, s ->  
    // eggs inside if should be replaced to a variable that has the value you want to find
    if (s == "eggs" ) {
        println("${s} ${index}")
    }
}
c
@Higor Oliveira thanks for your reply! I was chewing away at it and hit something similar, now trying to resolve type mismatches 😄 . I appreciate the help 🙂
v
Copy code
println(
    products
        .zip(0..<products.size)
        .filter { it.first == "eggs" }
        .joinToString(" ") { "${it.second}" }
)
🙌 1
c
Hi Björn - that is great! Thank you
👌 1
r
FYI, there's also a convenient
withIndex()
function, so that you don't need to zip with the index manually, it would look something like this:
Copy code
println(
    products
        .withIndex()
        .filter { it.value == "eggs" }
        .joinToString(" ") { "${it.index}" }
)
👌 1
👍 2
💯 1
c
@Riccardo Lippolis thank you for that example - very, very neat!