How to find the last occurrence of an element in a Scala List?
As of Scala 2.13, you can use findLast
to find the last element of a Seq
satisfying a predicate, if one exists:
val students = List(Student(1, 23), Student(2, 24), Student(3, 23))
students.findLast(_.age == 23) // Option[Student] = Some(Student(3, 23))
I think maybe you can achieve this by filter
with lastOption
, like:
list.filter(student => student.age == 23).lastOption
chengpohi
's and jwvh
's answers work, but will traverse the list twice or more.
Here's a generic way to find the last occurence that will only traverse the list once:
def findLast[A](la: List[A])(f: A => Boolean): Option[A] =
la.foldLeft(Option.empty[A]) { (acc, cur) =>
if (f(cur)) Some(cur)
else acc
}
We walk through the collection exactly once and always take the last element that matches our predicate f
.