Java Stream
interface has two methods i.e. findFirst() and findAny(). Both method looks very much similar but they may behave differently in certain conditions. In this post, learn the difference between findFirst() and findAny() methods.
1. Stream findFirst() method
1.1. Description
Optional<T> findFirst()
This method returns an Optional describing the first element of this stream. In case of stream has :
- defined encounter order – first element in encounter order in stream.
- no encounter order – any element may be returned.
The above theory is vaid for all sequential and parallel streams and the behavior of findFirst()
will not change.
1.2. Stream findFirst() example
import java.util.stream.Stream; public class Main { public static void main(String[] args) { //sequential stream Stream.of("one", "two", "three", "four") .findFirst() .ifPresent(System.out::println); //parallel stream Stream.of("one", "two", "three", "four") .parallel() .findFirst() .ifPresent(System.out::println); } }
Program output.
one one
2. Stream findAny() method
2.1. Description
Optional<T> findAny()
This method returns an Optional
describing the any element of this stream. In case of stream has :
- defined encounter order – any element may be returned.
- no encounter order – any element may be returned.
The above theory is vaid for all sequential and parallel streams and the behavior of findAny()
will not change.
In non-parallel streams,
findAny()
will return the first element in most of the cases but this behavior is not gauranteed.
Stream.findAny()
method has been introduced for performance gain in case of parallel streams, only.
2.2. Stream findAny() example
import java.util.stream.Stream; public class Main { public static void main(String[] args) { //sequential stream Stream.of("one", "two", "three", "four") .findAny() .ifPresent(System.out::println); //parallel stream Stream.of("one", "two", "three", "four") .parallel() .findAny() .ifPresent(System.out::println); } }
Program output.
one three
3. Stream findFirst() vs findAny() – Conclusion
In this post, we learned the difference between findFirst()
and findAny()
methods in Java 8 Stream API. In non-parallel streams, both may return the first element of the stream in most cases, but findAny()
does not offer any guarantee of this behavior.
Use findAny()
to get any element from any parallel stream in faster time. Else we can always use findFirst()
in most of the cases.
Reference :