CanOfBees
07/10/2024, 7:36 PMval 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!
val products = listOf("milk", "eggs", "bread", "cheese", "eggs", "greens")
products.forEachIndexed { index, s -> println("${s} ${index}") }
products.forEachIndexed { index, s -> ??? }
Higor Oliveira
07/10/2024, 7:42 PMval 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}")
}
}
CanOfBees
07/10/2024, 7:53 PMVampire
07/10/2024, 8:25 PMprintln(
products
.zip(0..<products.size)
.filter { it.first == "eggs" }
.joinToString(" ") { "${it.second}" }
)
CanOfBees
07/10/2024, 8:32 PMRiccardo Lippolis
07/11/2024, 7:13 AMwithIndex()
function, so that you don't need to zip with the index manually, it would look something like this:
println(
products
.withIndex()
.filter { it.value == "eggs" }
.joinToString(" ") { "${it.index}" }
)
CanOfBees
07/11/2024, 12:51 PMHuib Donkers
07/11/2024, 8:10 PM