How can i get the indices of items in a list that ...
# android
g
How can i get the indices of items in a list that match a condition?
t
I might do something like
Copy code
list.mapIndexedNotNull { index, item ->
      if (item == condition) {
          Pair(index, item)
      } else {
          null
      }
  }
a
Copy code
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)

val indices = numbers.indices
    .filter { numbers[it] % 2 == 0 }

println(indices)
println(numbers.slice(indices))

// output
// [1, 3, 5, 7]
// [2, 4, 6, 8]
t
Oh, that’s much nicer