Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent for Javas stream findFirst()

Anyone knows whats the Scala equivalent of the below java stream operation - findFirst()

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

Thank you

like image 818
Anand Avatar asked Nov 04 '15 04:11

Anand


People also ask

What is findFirst in Java Stream?

Stream findFirst() in Java with examples Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

What's the difference between findFirst () and findAny ()?

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

Which is faster findAny or findFirst?

Stream findFirst() vs findAny() – ConclusionUse findAny() to get any element from any parallel stream in faster time.

What is findAny in Java?

The findAny() method of the Java Stream returns an Optional for some element of the stream or an empty Optional if the stream is empty. Here, Optional is a container object which may or may not contain a non-null value.


1 Answers

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.

like image 110
tryx Avatar answered Oct 18 '22 23:10

tryx