Java Stream findAny() findFirst() Methods Tutorial

In this section we will learn what the Stream findAny() and findFirst() methods are and how to use them in Java.

What is Java Stream findAny() Method?

The Java Stream findAny() method is used to return an arbitrary element from a stream object.

Basically, when we want to get a random element of a stream object, we can use this method.

Note: this method is terminal and eager.

Java findAny() Method Syntax:

Optional<T> findAny()

findAny() Method Parameters:

The method does not take an argument.

findAny() Method Return Value:

The return value of this method is a random element of the target stream which is wrapped in an object of type Optional<T>.

Note: if the stream was empty, the return value of this method becomes an empty Optional object.

findAny() Method Exceptions:

The method might throw one exception and that is:

NullPointerException: we get this exception if the selected element from the stream was in fact null!

Example: using Stream findAny() method

import java.util.stream.Stream;
import java.util.Optional;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(20,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,2,7,86,54,5);
        Optional<Integer> option = stream.findAny();

        if (option.isPresent()){
            System.out.println(option.get());
        }

    }
}

Output:

20

Note: You might get a different result if you run this program.

What is Java Stream findFirst() Method?

The Java Stream findFirst() method is used to get the first element of a stream object and return that as a result.

Note: this method is terminal and eager.

Java findFirst() Method Syntax:

Optional<T> findFirst()

findFirst() Method Parameters:

The method does not take an argument.

findFirst() Method Return Value:

The return value of this method is the first element of the target stream object wrapped in an object of type Optional.

Note: if the target stream was empty, the return value of this method will be an empty Optional object.

findFirst() Method Exceptions:

The method might throw one exception and that is:

NullPointerException: we get this exception if the selected element from the stream was in fact null!

Example: using Stream findFirst() method

import java.util.stream.Stream;
import java.util.Optional;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(20,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,2,7,86,54,5);
        Optional<Integer> option = stream.findFirst();

        if (option.isPresent()){
            System.out.println(option.get());
        }

    }
}

Output:

20

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies