Java Stream findFirst()

The Stream findFirst() method is used with streams to retrieve the first element of the stream, assuming an order exists for the stream (for example, a list maintains its order, so findFirst() will return the first element of the list). If the stream is empty, it will return an empty Optional.

Syntax for findFirst() method

Optional<T> findFirst()

Example:-

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");

        Optional<String> firstFruit = fruits.stream()
                .findFirst();

        if (firstFruit.isPresent()) {
            System.out.println("First fruit: " + firstFruit.get());
        } else {
            System.out.println("No fruits found!");
        }
    }
}

Output:-

First fruit: apple

In this example, we have a list of fruits, and we use stream() to convert it into a stream. Then, we call findFirst() to get the first element of the stream. Finally, we use isPresent() to check if there is a result and get() to retrieve the value if it exists.

Java Stream findfirst() orElseThrow Example

In Java, we can use the findFirst().orElseThrow() combination to find the first element in a stream and throw an exception if the stream is empty. Here’s an example:

import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");

        try {
            String firstFruit = fruits.stream()
                    .findFirst()
                    .orElseThrow(() -> new NoSuchElementException("No fruits found!"));

            System.out.println("First fruit: " + firstFruit);
        } catch (NoSuchElementException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:-

First fruit: apple
  1. We call findFirst() to retrieve the first element of the stream, and then we use orElseThrow() to specify that if the stream is empty, it should throw a NoSuchElementException with a custom error message.
  2. We use a try-catch block to handle the potential exception. If the stream is not empty, the first fruit is printed. If the stream is empty, a NoSuchElementException is thrown with the specified error message, and we catch and handle it to print the error message to the console.

Java stream findfirst() example with condition

We can use the Java Stream findFirst() method in combination with the filter() method to find the first element in a Java stream that satisfies a specific condition. Here’s an example:

Suppose We have a list of numbers, and you want to find the first even number in the list:

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 3, 5, 2, 4, 6);

        Optional<Integer> firstEvenNumber = numbers.stream()
                .filter(number -> number % 2 == 0) // Filter for even numbers
                .findFirst();

        if (firstEvenNumber.isPresent()) {
            System.out.println("First even number: " + firstEvenNumber.get());
        } else {
            System.out.println("No even numbers found!");
        }
    }
}

Output:-

First even number: 2

It found the first even number in the list, which is 2.

Java Stream findfirst() example using map()

We can use the findFirst() method along with the Stream map() function to find the first element in a stream that matches a certain condition and then perform some transformation on it. Here’s an example of how you can use findFirst() and map() together:

Suppose you have a list of integers and you want to find the first even number in the list and then double it. You can do this using Java streams:

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamFindFirstMapExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 3, 5, 2, 4, 6, 7, 8, 9, 10);

        Optional<Integer> result = numbers.stream()
                .filter(num -> num % 2 == 0) // Filter for even numbers
                .findFirst() // Find the first even number
                .map(evenNum -> evenNum * 2); // Double the first even number

        if (result.isPresent()) {
            System.out.println("First even number doubled: " + result.get());
        } else {
            System.out.println("No even numbers found.");
        }
    }
}

Output:- First even number doubled: 4

The result is an Optional<Integer> that either contains the doubled value of the first even number or is empty if there are no even numbers in the list. We check if the result is present using isPresent() and then either print the doubled value or a message indicating that no even numbers were found.

Note – Always try to call isPresent() after findFirst() and before get() method to avoid NoSuchElementException. Below code will throw NoSuchElementException.

package com.javatute.stream;
import java.util.*;
public class JavaStreamFindFirst {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 3, 5);
        Optional<Integer> optional = numbers.stream().filter(n->n%2==0).findFirst();
        System.out.println(optional.get());
    }
}

Output:-

Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)
	at com.javatute.stream.JavaStreamFindFirst.main(JavaStreamFindFirst.java:7)
Process finished with exit code 1

Important points related Java Stream findFirst() method

  1. Returns an Optional: The findFirst() method is a terminal operation in Java Streams. It returns an Optional<T>.
  2. Short-Circuiting: The findFirst() is a short-circuiting operation, meaning it doesn’t process all elements of the stream. Once it finds the first element that satisfies the condition, it stops processing and returns that element.
  3. Common Usage: It is often used in conjunction with other stream operations like filter() to find the first element that meets certain criteria. For example, you can use filter() to filter elements based on a condition and then use findFirst() to retrieve the first element that passes the filter.

Ten objective questions related to the Java 8 Stream findFirst() method.

Question 1: What is the return type of the findFirst() method in Java 8 Streams?

A. int
B. Optional<T>
C. List<T>
D. Stream<T>

Question 2: Is findFirst() a terminal operation in Java Streams?

A. Yes
B. No

Question 3: What happens if you call findFirst() on an empty stream?

A. It returns null.
B. It throws a NoSuchElementException.
C. It returns an empty Optional.
D. It throws a NullPointerException.

Question 4: In a stream of integers, which of the following findFirst() calls will return the first even number?

A. .findFirst(num -> num % 2 == 0)
B. .findFirst(num -> num > 5)
C. .findFirst()
D. .findFirst(num -> num < 0)

Question 5: Is the order of elements in a stream significant when using findFirst()?

A. Yes, it always returns the first element added to the stream.
B. Yes, it always returns the last element added to the stream.
C. No, it returns any matching element without guaranteeing a specific order.
D. No, it returns the element with the highest value.

Question 6: What does findFirst() return if there are no elements that match the specified condition?

A. null
B. 0
C. Optional.empty()
D. Optional.of(0)

Question 7: Which of the following code snippets correctly uses findFirst() to find the first element of a list of strings?

A. list.stream().findFirst().get()
B. list.stream().findFirst().orElse(null)
C. list.stream().findFirst().orElseThrow(() -> new NoSuchElementException())
D. list.stream().findFirst().ifPresent(System.out::println)

Question 8: Which of the following methods is used to check if an element is present in the Optional returned by findFirst()?

A. isPresent()
B. isEmpty()
C. hasValue()
D. contains()

Question 9: What does the findFirst() method return when used on a parallel stream?

A. It returns the first element from the parallel stream.
B. It returns the last element from the parallel stream.
C. It throws a ConcurrentModificationException.
D. It returns any matching element from the parallel stream.

Question 10: In a stream of objects, which of the following code snippets correctly finds the first object with a specific property?

A. .findFirst(obj -> obj.property == value)
B. .findFirst(obj -> obj.property.equals(value))
C. .findFirst(obj -> obj.property.contains(value))
D. .findFirst(obj -> obj.property.startsWith(value))

Answers:

  1. B. Optional<T>
  2. A. Yes
  3. C. It returns an empty Optional.
  4. A. .findFirst(num -> num % 2 == 0)
  5. C. No, it returns any matching element without guaranteeing a specific order.
  6. C. Optional.empty()
  7. B. list.stream().findFirst().orElse(null)
  8. A. isPresent()
  9. D. It returns any matching element from the parallel stream.
  10. B. .findFirst(obj -> obj.property.equals(value))

That’s all about Java Stream findFirst() method.

Other Java 8 Stream examples.