Anyone knows whats the Scala equivalent of the below java stream operation - findFirst()
lst.stream()
.filter(x -> x > 5)
.findFirst()
Thank you
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.
The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.
Stream findFirst() vs findAny() – ConclusionUse findAny() to get any element from any parallel stream in faster time.
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.
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.
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