Colton Idle
01/21/2022, 6:29 AMlist.indexOfFirst
and
list.first
but is there some way to get both?ephemient
01/21/2022, 6:35 AMlist.withIndex().first { predicate(it.value) }
Albert Chang
01/21/2022, 6:58 AMArrayList
), getting the index and then retrieving the value using the index is more efficient as the access is O(1) and there’s no additional object allocations which isn’t the case when using withIndex()
.ephemient
01/21/2022, 7:12 AMLinkedList
is RandomAccess
Colton Idle
01/21/2022, 7:30 AMephemient
01/21/2022, 7:39 AMval (index, value) = run {
list.forEachIndexed { index, value ->
if (predicate(value)) return@run IndexedValue(index, value)
}
throw NoSuchElementException()
}
or something, but otherwise, pick fast (indexOf) or concise (withIndex)Colton Idle
01/21/2022, 7:45 AMwithIndex
Thanks as always @ephemient and @Albert Chang