Wednesday, November 24, 2021

Java Stream - findAny() With Examples

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

  1. Java Stream - findFirst() With Examples
  2. Java Stream - max() With Examples
  3. collect() Method And Collectors Class in Java Stream API

You may also like-

  1. Adding Tomcat Server to Eclipse
  2. JVM Run-Time Data Areas - Java Memory Allocation
  3. Types of JDBC Drivers
  4. Java ArrayBlockingQueue With Examples
  5. What Are JVM, JRE And JDK in Java
  6. How to Read Input From Console in Java
  7. Angular First App - Hello world Example
  8. Spring Component Scan to Automatically Discover Beans

No comments:

Post a Comment