Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between findAny() and findFirst() in Java 8

I am little confused between Stream#findAny() and Stream#findFirst() of the Stream API in Java 8.

What I understood is that both will return the first matched element from the stream, for example, when used in conjunction with filter?

So, why two methods for the same task? Am I missing something?

like image 577
Mandeep Rajpal Avatar asked Feb 12 '16 09:02

Mandeep Rajpal


People also ask

What is the difference between the anyMatch () and findAny () stream methods?

Stream#anyMatch() returns a boolean while Stream#findAny() returns an object which matches the predicate. They almost do the same work. anyMatch is a short-circuit operation, but filter will always process the whole stream.

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.

Is findFirst terminal operation?

Java 8 Stream#findFirst() is a short-circuiting terminal operation. Meaning it will stop generating the stream once an element is found (usually used with a filter() operation).


1 Answers

What I understood is that both will return the first matched element from the stream, for example, when used in conjunction with filter?

That's not true. According to the javadoc, Stream#findAny():

Returns an Optional<T> describing some element of the stream, or an empty Optional<T> if the stream is empty. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations;

while Stream.findFirst() will return an Optional<T> describing strictly the first element of the stream. The Stream class doesn't have a .findOne() method, so I suppose you meant .findFirst().

like image 64
Konstantin Yovkov Avatar answered Sep 28 '22 04:09

Konstantin Yovkov