What is the findAny method of Stream Interface?
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.
Syntax
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.
Example
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:
- Created an
ArrayListwith elements:
1,2,3
- Then, we created a
streamfrom theArrayListwith thestream()method.
numbers.stream() // returns numbers ArrayList as Stream
-
After we converted into
stream, we called thefindAnymethod. ThefindAnymethod will return from theany element in most cases it returns the first element streamas anOptionalobject. -
We used the
isPresent()method to check if the returnedOptionalobject contains a value, which will returntrueif the value present in theOptional. -
At last, the value from the
Optionalis taken through thegetmethod, and prints the element selected by thefindAnymethod.