Anyone knows whats the Scala equivalent of the below java stream operation - findFirst()
lst.stream()
.filter(x -> x > 5)
.findFirst()
Thank you
Anyone knows whats the Scala equivalent of the below java stream operation - findFirst()
lst.stream()
.filter(x -> x > 5)
.findFirst()
Thank you
You can simple use lst.find(_ > 5)
which will return an Option
. This is basically the same as (but more efficient than) writing lst.filter(_ > 5).headOption
which will also return an Option
or swapping headOption
for head
(highly discouraged) which will throw an exception if nothing is found.
As @Aivean noted:
scala> List(1,2,3,4,5,6,7,8,9,10).view.find(_ > 5)
res0: Option[Int] = Some(6)
See these questions:
In Scala, what does "view" do?
What is the difference between the methods iterator and view?