VOOZH about

URL: https://www.geeksforgeeks.org/java/java-stream-findany-with-examples/

⇱ Java Stream findAny() with examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Stream findAny() with examples

Last Updated : 26 Sep, 2023

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.

[tabbyending]

Output
2

Example 2: findAny() function on Stream of Strings.

[tabbyending]

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.

[tabbyending]

Output
16

Difference Between 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.

Note: Finding the first element is more constraining in parallel. If you don’t care about which element is returned, use findAny because it’s less constraining when using parallel streams.

Comment