Difference between findAny and findFirst of Java Stream API

Difference between findAny and findFirst of Java Stream API :

findAnyand findFirstare two methods defined in Java Stream API. Both of these methods return one element from a stream. Both of these methods returns one Optional value holding one member of the list.

Definition of findFirst and findAny :

These methods are defined as below:

Optional<T> findFirst()

and

Optional<T> findAny()

findFirst returns the first element of a stream and findAny returns any element from the stream.

Example of findFirst and findAny :

Let’s take a look at one example to understand how to use findFirst and findAny:

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

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

        Optional findAnyValue = integerArray.stream().findAny();
        Optional findFirstValue = integerArray.stream().findFirst();

        System.out.println(findAnyValue);
        System.out.println(findFirstValue);
    }
}

In this example, we created one List of integer integerArray. We are calling findAny and findFirst in the stream of this list.

It will print the below output:

Optional[1]
Optional[1]

Both returned the same result, but actually both are different.

Difference between findFirst and findAny:

For non parallel streams, in most cases, findAny returns the first element of the stream. But that doesn’t mean that findAny and findFIrst both are same. This behavior is not guaranteed.

Exception thrown:

Both of these methods throws NullPointerException if it selects a null value in the stream.

You might also like: