Issue
I need to find first element in a list which fits predicate. But I need to check with it position in predicate.
list.findXXX { index, item ->
index > 19 && item.active
}
Is there such a function?
Solution
There is no such function yet, but you can easily write one yourself. It is not a lot of effort at all.
public inline fun <T> Iterable<T>.findIndexed(predicate: (Int, T) -> Boolean): T? {
forEachIndexed { i, e -> if (predicate(i, e)) return e }
return null
}
Alternatively, in general you can use a filterIndexed
to first filter out the indexes that you want to exclude:
list
// .asSequence() // if you want to be lazy
.filterIndexed { i, _ -> i > 19 }
.find { item -> item.active }
In fact, you could just put the entire condition in filterIndexed
and use firstOrNull
afterwards. It just may not read as nicely as find
.
Of course in this specific case you can also just drop
the first 20.
Answered By - Sweeper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.