Issue
Working on Android/Kotlin app, I'm having trouble finding indices of second and third element in the array that fulfills some condition. Since I know there are 4 elements in the array that would return true, i can use indexOfFirst() and indexOfLast(), but that way, I get only the first and the fourth indices.
val array: Array<String>
val firstOne = array.indexOfFirst(::func)
val lastOne = array.indexOfLast(::func)
fun func(element: String): Boolean{
return element=="a" }
I tried using filterIndexed() but that returns a new list, and only values are saved, but not indices of the elements in there, which I need
Solution
You can use withIndex
to get the items with their indices and then filter that.
val elements: List<IndexedValue<String>> = array.withIndex().filter { (_, value) -> func(value) }
If you only need indices:
val indices = array.withIndex().filter { (_, value) -> func(value) }.map { it.index }
Or if you want to assign each of these to a variable instead of getting a list:
val iterator = array.asSequence().withIndex()
.filter { (_, value) -> func(value) }
.iterator()
val (firstIndex, firstValue) = iterator.next()
val (secondIndex, secondValue) = iterator.next()
val (thirdIndex, thirdValue) = iterator.next()
val (fourthIndex, fourthValue) = iterator.next()
If you only need indices:
val iterator = array.asSequence().withIndex()
.filter { (_, value) -> func(value) }
.map { it.index }
.iterator()
val first = iterator.next()
val second = iterator.next()
val third = iterator.next()
val fourth = iterator.next()
Answered By - Tenfour04
Answer Checked By - Clifford M. (JavaFixing Volunteer)