The findFirst
method will return an optional
isPresent()
will return true, and get()
will return the value.
In the case that the stream is empty, the empty optional object is returned.
Optional<T> findFirst()
If the stream has defined the encounter order, the findFirst()
method will return the first element in the encounter order.
If the stream has not defined the encounter order, the findFirst()
method will return any element from the stream. For example, the stream created from the List object is ordered, so we can know which element will be returned by the findFirst
method. However, the stream created from the HashSet is unordered, so we cannot know which element will be returned by the findFirst
method.
The above cases are the same for both the stream and parallel stream.
The NullPointerException
is thrown if the stream contains a null value and the findAny
method selected that null element.
import java.util.Optional;import java.util.ArrayList;class FindFirstExample {public static void main( String args[] ) {ArrayList<Integer> numbers = new ArrayList<>();numbers.add(1);numbers.add(2);numbers.add(3);System.out.println("Calling findFirrst method");Optional<Integer> firstElement = numbers.stream().findFirst();System.out.println("Checking if value present in returned optional - " + firstElement.isPresent());System.out.println("The first element of stream is " + firstElement.get());}}
In the above code, we:
1,2,3
stream()
method to create a stream from the ArrayList, which returns an ordered stream.numbers.stream() // returns numbers ArrayList as Stream
After we converted into stream, we called the findFirst
method. The findFirst
method will return the first element from the stream as an optional object. The first element is returned if the stream has an encounter order; otherwise, any element can be returned.
Checked if the returned optional object contains a value through the isPresent()
method, which will return true
if the value is present.
At last, we used the get
method to take the value from Optional
, and printed the element selected by the findFirst
method.