Friday, September 5, 2025
HomeLanguagesJavaJava Stream findAny() with examples

Java Stream findAny() with examples

Stream findAny() returns an Optional (a container object which may or may not contain a non-null value) describing some element of the stream, or an empty Optional if the stream is empty.

Syntax of findAny()

Optional<T> findAny()

Parameters

1. Optional is a container object which may or may not contain a non-null value and
2. T is the type of object and the function

Returns an Optional describing some element of this stream, or an empty Optional if the stream is empty.

Exception : If the element selected is null,

NullPointerException is thrown.

Note: findAny() is a terminal-short-circuiting operation of Stream interface. This method returns any first element satisfying the intermediate operations. This is a short-circuit operation because it just needs ‘any’ first element to be returned and terminate the rest of the iteration.

Examples of Java Stream findAny()

Example 1: findAny() method on Integer Stream.

Java

// Java code for Stream findAny()
// which returns an Optional describing
// some element of the stream, or an
// empty Optional if the stream is empty.
import java.util.*;

class GFG {
    // Driver code
    public static void main(String[] args)
    {
        // Creating a List of Integers
        List<Integer> list = Arrays.asList(2, 4, 6, 8, 10);

        // Using Stream findAny() to return
        // an Optional describing some element
        // of the stream
        Optional<Integer> answer = list.stream().findAny();

        // if the stream is empty, an empty
        // Optional is returned.
        if (answer.isPresent()) {
            System.out.println(answer.get());
        }
        else {
            System.out.println("no value");
        }
    }
}

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS