The findAny
method returns an Optional
object with some element of the stream as a value. Optional
object refers to a container object which may or may not contain a non-null value. If a value is present, isPresent()
will return true, and get()
will return the value.
In the case that the stream is empty, the empty Optional
is returned.
Optional<T> findAny()
The selection behavior of the element is nondeterministic and the findAny
method will select any element from the stream.
The NullPointerException
is thrown if the stream contains a null
value and the findAny
method selected that null
element.
In a non-parallel operation, the findAny
method will mostly return the first element from the stream
, but this behavior is not guaranteed. In a parallel operation, we cannot predict which element will be returned.
import java.util.Optional;import java.util.ArrayList;class FindAnyExample {public static void main( String args[] ) {ArrayList<Integer> numbers = new ArrayList<Integer>();numbers.add(1);numbers.add(2);numbers.add(3);System.out.println("Calling findAny method");Optional<Integer> anyElement = numbers.stream().findAny();System.out.println("Checking if value present in optional - " + anyElement.isPresent());System.out.println("The picked element is " + anyElement.get());}}
In the code above, we have:
ArrayList
with elements:1,2,3
stream
from the ArrayList
with the stream()
method.numbers.stream() // returns numbers ArrayList as Stream
After we converted into stream
, we called the findAny
method. The findAny
method will return stream
as an Optional
object.
We used the isPresent()
method to check if the returned Optional
object contains a value, which will return true
if the value present in the Optional
.
At last, the value from the Optional
is taken through the get
method, and prints the element selected by the findAny
method.