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 ?
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With