Java Stream findAny() with examples

06 Dec, 2018
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.
findAny() V/s findFirst() :
The findAny() method returns any element from a Stream but there might be a case where we require the first element of a filtered stream to be fetched. When the stream being worked on has a defined encounter order(the order in which the elements of a stream are processed), then findFirst() is useful which returns the first element in a Stream.
Syntax :
Optional<T> findAny()

Where, Optional is a container object which
may or may not contain a non-null value 
and T is the type of objects 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.
Example 1 : findAny() method on Integer Stream.
// 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");        }    }}
Output :
2

Example 2 : findAny() function on Stream of Strings.
// 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 Strings        List<String> list = Arrays.asList("Geeks", "for",                                          "GeeksQuiz", "GFG");          // Using Stream findAny() to return        // an Optional describing some element        // of the stream        Optional<String> 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");        }    }}
Output :
Geeks

Note : The behavior of Stream findAny() operation is explicitly non-deterministic i.e, it is free to select any element in the stream. Multiple invocations on the same source may not return the same result.Example 3 : findAny() method to return the elements divisible by 4, in a non-deterministic way.
// 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.OptionalInt;import java.util.stream.IntStream;  class GFG {          // Driver code    public static void main(String[] args) {              // Creating an IntStream    IntStream stream = IntStream.of(4, 5, 8, 10, 12, 16)                       .parallel();          // Using Stream findAny().     // Executing the source code multiple times    // may not return the same result.    // Every time you may get a different     // Integer which is divisible by 4.    stream = stream.filter(i -> i % 4 == 0);      OptionalInt answer = stream.findAny();    if (answer.isPresent())     {        System.out.println(answer.getAsInt());    }}}
Output :
16

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java