In Java Stream API findAny() method is used to return some element of the stream. Method returns the element as an Optional or an empty Optional if the stream is empty.
Syntax of the Stream.findAny() method is as follows-
Optional<T> findAny()
findAny() is a short-circuiting terminal operation meaning it may terminate in finite time when presented with infinite input.
The element of the Stream returned by findAny() is random in nature though in most of the case it returns the first element of the stream just like findFirst() method but this behavior is not guaranteed.
Java Stream findAny() examples
1. An example to get some element from a Stream of Integers.
import java.util.Arrays; import java.util.List; import java.util.Optional; public class StreamFindAny { public static void main(String[] args) { List<Integer> list = Arrays.asList(3, 9, 1, 9, 7, 8); Optional<Integer> anyNumFromStream = list.stream().findAny(); if(anyNumFromStream.isPresent()) { System.out.println("Element in the Stream- " + anyNumFromStream.get()); }else { System.out.println("No element found"); } } }
Output
Element in the Stream- 3
2. You can also use findAny() method along with other Stream operations to get any element from the resultant stream. For example using filter method to filter out elements which are less than 5 and then getting any element from the resultant stream.
public class StreamFindAny { public static void main(String[] args) { List<Integer> list = Arrays.asList(3, 2, 6, 2, 7, 8); list.stream() .filter(e -> e > 5) .findAny() .ifPresent(System.out::println); } }
Output
6
That's all for this topic Java Stream - findAny() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment