Find last item in an indexed sequence matching a predicate

Viewed 1185

What is a proper Scala way to find a last element in the indexed sequence (like Vector, Array or ArrayBuffer) matching a predicate, assuming we want the solution to be fast when the element exists near the sequence end?

One could use seq.reverse.find to achieve this, but that is O(N), as reverse makes a complete copy of the sequence.

3 Answers

Starting Scala 2.13 you can use findLast, which is the reverse of find and applies the predicate to match from the end of the collection:

Array((10, 'a'), (20, 'b'), (30, 'c'), (20, 'd')).findLast(_._1 == 20)
// Option[(Int, Char)] = Some(20, 'd')
Related