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 Optional that 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("The stream is empty.");
    }
  }
}

Output: The first name which length is greater than 5: Melissa


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("The stream is empty.");
    }
  }
}

Output: The stream is empty.


Here, it couldn’t find any even number in the stream, so it returned the empty Optional.

That’s it!

 

Leave a Reply

Your email address will not be published.