What is the findFirst method of the Stream Interface?

The findFirst method will return an optionalA 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. object with the first element of the stream as a 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 the findFirst method. However, the stream created from the HashSet is unordered, so we cannot know which element will be returned by the findFirstmethod.

  • 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.

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 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.

Free Resources