Difference Between FindFirst() And FindAny() In Java 8 – Detailed Guide

The Java 8 Stream supports various aggregate operations on a stream of elements.

You can use Stream’s .findFirst() and .findAny()methods to get an element from the stream of elements with .findFirst() to get the first element and later .findAny() to get any element.

In this tutorial, you will learn about the behavioural difference between Java 8 Stream’s .findFirst() and .findAny() in detail.

Stream.findFirst()

The Java 8 Stream interface’s .findFirst() method is used to get the first element of the stream.
Syntax

Optional<T> findFirst();

Parameters

  • T – Denotes the date type of elements in the stream.
  • Returns:
    – If stream is not empty: Optional element describing the first element of stream.
    – If the stream is empty: Empty Optional is returned.
    – If the selected element is null: NullPointerException is thrown.

Check this tutorial to get more details on the .findFirst() method, How to find the first element using Java 8 Predicate

Use this method to get the first element in a stream, and If the stream doesn’t have any order, it can return any element.

Code

    import java.util.Arrays;  
    import java.util.List;  
    import java.util.function.Predicate;

    //main
    List<Integer> numbers = Arrays.asList(2,5,12,9,10,1); 
    Integer number = numbers.stream().peek(item->System.out.println("visited value: "+item)).filter(value -> (value > 5)).findFirst().get();  
    System.out.println("Number: "+number);

Output

    visited value: 9
    visited value: 1
    visited value: 2
    visited value: 12
    visited value: 5
    Number: 12
    //next run return
    ...
    Number: 12
    //next run return
    ...
    Number: 12

In the above example, the first element that satisfies the condition is 12, which is returned by the .findFirst() method.
If the first element is null, then a NullPointerException is thrown as shown below,
Code

    //main
    List<String> names = Arrays.asList(null, "Alex", "Priya", null, "Jessica", "Ameer");  
    Optional<String> name = names.stream().findFirst();  
    System.out.println(name.get());

Output

    Exception in thread "main" java.lang.NullPointerException
        at java.base/java.util.Objects.requireNonNull(Objects.java:233)

Stream.findAny()

The Java 8 Stream interface’s .findAny() method can be used to get any stream element without specific criteria.
This method is designed to select any element in the stream, and as a result, it may not guarantee to return the same element when invoked parallelly multiple times on the same source.

Syntax
Optional<T> findAny();
Parameters

  • T – Denotes the date type of elements in the stream.
  • Returns:
    – If stream is not empty: Optional element describing the some element of stream.
    – If the stream is empty: Empty Optional is returned.
    – If the selected element is null: NullPointerException is thrown.

Use this method where ever random value selection is applicable with no expectation always to have the same value returned for a given dataset.
Maximum performance can be achieved with the parallel stream.

Code

    import java.util.Arrays;  
    import java.util.List;  
    import java.util.function.Predicate;

    //main
    List<Integer> numbers = Arrays.asList(2,5,12,9,10,1);  
    Predicate<Integer> predicate = value -> (value > 5);
    Integer number = numbers.stream().parallel().peek(item->System.out.println("visited value: "+item)).filter(predicate).findAny().get();  
    System.out.println("Number: "+number);

Output

    visited value: 10
    visited value: 5
    visited value: 9
    visited value: 1
    Number: 10
    //next run may return
    ...
    Number: 12
    //next run may return
    ...
    Number:9

The above example, you can see .findAny() may return different values on each new parallel run.

Related Topics

Leave a Comment