Scala equivalent for Javas findFirst () thread

Does anyone know what Scala is equivalent to for the java thread operation below - findFirst ()

lst.stream() .filter(x -> x > 5) .findFirst() 

thanks

+5
source share
2 answers

You can simply use lst.find(_ > 5) , which will return Option . This is basically the same (but more efficient than) lst.filter(_ > 5).headOption , which will also return an Option or headOption swap for head (very discouraged), which throws an exception if nothing is found.

+10
source

As @Aivean pointed out:

 scala> List(1,2,3,4,5,6,7,8,9,10).view.find(_ > 5) res0: Option[Int] = Some(6) 

See the following questions:

In Scala, what does “view” do?

What is the difference between iterator methods and presentation?

-1
source

Source: https://habr.com/ru/post/1235166/


All Articles