The Stream.findAny() returns an Optional describing any element of the specified stream if Stream is non-empty. It returns an empty Optional
if the stream is empty.
In non-parallel streams, findAny()
will return the first element in most cases, but this behavior is not guaranteed. The Stream.findAny()
method has been introduced for performance gain in the case of parallel streams, only.
1. Syntax
Optional<T> findAny()
- The
findAny()
method is a terminal short-circuiting operation. - The
findAny()
method returns anOptional
. - The
Optional
contains the value as any element of the given stream, if Stream is non-empty. The returned element is the first element in most cases. - The
Optional
contains the empty value, if Stream is empty. - If the element selected is
null
, NullPointerException is thrown. - For all the sequential and parallel streams, it may return any element. The behavior of
findAny()
does not change by the parallelism of the Stream. - Similarly, there is no guaranteed behavioral difference in case of a stream has a defined encounter order or has no encounter order at all.
2. Stream.findAny() Example
In the given example, we are using the finaAny()
method to get any element from the Stream
. The method returns an Optional.
If the stream is empty, we get an empty optional.
Optional optional = Stream.empty().findAny();
Assertions.assertTrue(optional.isEmpty());
For non-empty streams, we get an Optional with a value.
Optional optional = Stream.of("one", "two", "three", "four").findAny();
Assertions.assertTrue(optional.isPresent());
Assertions.assertEquals("one", optional.get());
For parallel streams, the findAny() behaves the same as above, but the optional value is not predictable.
Optional optional = Stream.of("one", "two", "three", "four").parallel().findAny();
Assertions.assertTrue(optional.isPresent());
3. Difference between findFirst() vs findAny()
In non-parallel streams, findFirst()
and findAny()
, 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 a faster time. Else we can always use findFirst()
in most cases.
Happy Learning !!
Comments