Java Stream findFirst()

In this guide, you will learn about the Stream findFirst() method in Java programming and how to use it with an example.

1. Stream findFirst() Method Overview

Definition:

The Stream.findFirst() method is a terminal operation that returns an Optional describing the first element of the stream, or an empty Optional if the stream is empty. 

It is particularly useful in parallel streams where it is more performance-friendly compared to findAny() as it doesn't need to return any element, just the first one.

Syntax:

Optional<T> findFirst()

Parameters:

- None.

Key Points:

- It's a terminal operation, which means it ends the stream and produces a result.

- The method returns an Optional to handle the cases where the stream might be empty and prevent NullPointerException.

- It is deterministic, meaning it will consistently return the first element of the stream if it exists.

- In parallel streams, findFirst() is less efficient than findAny() as it must preserve the encounter order.

- It is a short-circuiting operation; it doesn't need to process the entire stream if the first element has been found.

2. Stream findFirst() Method Example

import java.util.stream.Stream;

public class StreamFindFirstExample {
    public static void main(String[] args) {
        Stream<String> fruitsStream = Stream.of("Cherry", "Banana", "Apple", "Elderberry", "Date");

        // Using findFirst on a stream
        fruitsStream.findFirst().ifPresent(System.out::println);

        // Using findFirst on an empty stream
        Stream<String> emptyStream = Stream.empty();
        emptyStream.findFirst().ifPresent(System.out::println);  // This won't print anything
    }
}

Output:

Cherry

Explanation:

In the provided example:

1. We first call findFirst() on a stream of fruit names, which retrieves the first fruit "Cherry".

2. Then, we call findFirst() on an empty stream. Since there's no element in the stream, nothing gets printed.

The result showcases how findFirst() operates, retrieving the first element if it exists and gracefully handling the cases where the stream is empty.

Comments