I want to find an item in a list. When I find it, ...
# getting-started
c
I want to find an item in a list. When I find it, I also want the index of it. I have found
Copy code
list.indexOfFirst
and
Copy code
list.first
but is there some way to get both?
e
Copy code
list.withIndex().first { predicate(it.value) }
👀 1
a
If your list is a random access list (such as
ArrayList
), 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()
.
👍 1
e
this is true, and almost every list you will commonly encounter except
LinkedList
is
RandomAccess
c
So theres basically no way to do it in one call (what Albert is recc'ing)? Basically just find the index first, then grab the item with said index. No fancy idiomatic kotlin function or something available?
e
you could put a nice wrapper around
Copy code
val (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)
c
fast it is! Glad I wasn't missing any cool function I just didn't stumble upon, but I did TIL
withIndex
Thanks as always @ephemient and @Albert Chang