Streams – findFirst() operation

Stream findFirst() is a terminal operation in Java, and we use it to find an element in the Stream. As soon as it finds the first element, the flow stops.

The findFirst() method returns Optional. If the element is found, it will return Optionalwhich contains that value. Otherwise, it will return an empty Optional. We will cover the Optional class later in this tutorial.

Syntax

Optional<T> findFirst()

Java Stream findFirst() operation – examples

Example 1

Find the first element in the stream:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(3, 7, 9, 12));

    Optional<Integer> resultOptional = numbers.stream().findFirst();

    if (resultOptional.isPresent()) { // checking if Optional contains any value
      System.out.println("The first element in the stream is: " + resultOptional.get()); // getting the value from Optional
    } else {
      System.out.println("The stream is empty.");
    }
  }
}
Output: The first element in the stream is: 3

Example 2

Find the first element which length is greater than 5:

class Test {

  public static void main(String[] args) {
    List<String> names = new ArrayList<>(Arrays.asList("Steve", "John", "Melissa", "Megan", "Norton", "Alexander"));

    Optional<String> nameOptional = names.stream()
            .filter(name -> name.length() > 5)
            .findFirst();

    if (nameOptional.isPresent()) { // checking if Optional contains any value
      System.out.println("The first name which length is greater than 5: " + nameOptional.get()); // getting the value from Optional
    } else {
      System.out.println("No element with length greater than 5 was found.");
    }
  }
}
Output: The first name which length is greater than 5: Melissa
 
For a reminder on the filter() operation, please refer to this tutorial Streams – filter() operation.

Example 3

Find the first even number in the stream:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(3, 7, 9, 15));

    Optional<Integer> resultOptional = numbers.stream()
            .filter(num -> num % 2 == 0)
            .findFirst();

    if (resultOptional.isPresent()) { // checking if optional contains any value
      System.out.println("The first element in the stream is: " + resultOptional.get()); // getting the value from Optional
    } else {
      System.out.println("No even number was found.");
    }
  }
}
Output: The stream is empty.
 
Here, it couldn’t find any even number in the stream, so it returned the empty Optional.
 
I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.

 

Leave a Reply

Your email address will not be published. Required fields are marked *