What is the findFirst method of the Stream Interface?
The findFirst method will return an optionalisPresent() will return true, and get() will return the value.
In the case that the stream is empty, the empty optional object is returned.
Syntax
Optional<T> findFirst()
Return values
-
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 thefindFirstmethod. However, the stream created from the HashSet is unordered, so we cannot know which element will be returned by thefindFirstmethod. -
The above cases are the same for both the stream and parallel stream.
-
The
NullPointerExceptionis thrown if the stream contains a null value and thefindAnymethod selected that null element.
Code
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());}}
Explanation
In the above code, we:
- Created an ArrayList with the elements:
1,2,3
- Used the
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
findFirstmethod. ThefindFirstmethod 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 returntrueif the value is present. -
At last, we used the
getmethod to take the value fromOptional, and printed the element selected by thefindFirstmethod.