Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the last occurrence of an element in a Scala List?

Tags:

scala

I have a List of Students from which I want to find the last matching student whose age is 23.

I know that find() method gives us the first matching occurrence as shown below:

case class Student(id: Int, age: Int)

val students = List(Student(1, 23), Student(2, 24), Student(3, 23))

val firstStudentWithAge23 = students.find(student => student.age == 23)
// Some(Student(1, 23))

This code gives me the first matching student. But I need the last matching student.

For now, I am using reverse method followed by find:

val lastStudentWithAge23 = students.reverse.find(student => student.age == 23)
// Some(Student(3,23))

This gives me the last matching student.

But this doesn't not seem to be a good approach since the whole list has to be reversed first. How can I achieve this in a better yet functional way ?

like image 234
oblivion Avatar asked Dec 03 '17 14:12

oblivion


People also ask

What is Scala last?

In Scala Stack class , the last() method is utilized to return the last element of the stack. Return Type: It returns the last element of the stack.

How do you get the index of an element in a list in Scala?

Scala List indexOf() method with example. The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument. Return Type: It returns the index of the element present in the argument.

How do you define a list in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.


1 Answers

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))
like image 125
NthPortal Avatar answered Sep 19 '22 07:09

NthPortal