Suma Suma - 2 years ago 77
Scala Question

Find last item in an indexed sequence matching a predicate

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.

Answer Source

Vector.reverseIterator is O(1).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download