Hi all, is this the best approach of finding a spe...
# announcements
s
Hi all, is this the best approach of finding a specific item in a list based on a certain predicate and returning the item's index and value at once?
Copy code
list.asSequence().withIndex().find { some predicate }
s
Not sure if
asSequence()
is necessary...
s
I think
asSequence()
makes sense because then the values are computed lazily. So if the predicate matches the second item of the list out of 500, then only two
IndexedValue
needed to be created and 498
IndexedValue
where never created 🙂
m
withIndex
on a list actually returns a lazy iterable: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/with-index.html
s
@marstran No 😉
Sequence
has it's own implementation of withIndex.
m
Sure, but read the doc. It says "Returns a lazy
Iterable
that wraps each element ...".
s
Regarding an
Iterable
you're correct, but that's the reason why I convert the list to a
Sequence
first
m
But you don't need to, because the iterable returned by
list.withIndex()
is just as lazy as the sequence.
It doesn't create the other 498 indexed values.
s
Ah, now I get what you mean 👍🏼