Streams – findAny() operation

Stream findAny() is a terminal operation in Java, and it is used to find an element in the stream.
As soon as it finds the element, the flow stops. It is introduced mainly for working with parallel streams.

In non-parallel streams, findFirst() and findAny(), both may return the first element of the stream in most cases. But findAny() does not offer any guarantee of this behavior.

The findAny() method returns Optional. If the element is found, it will return Optional that contains that value. Otherwise, it will return an empty Optional.

Syntax

Optional<T> findAny()


Java Stream findAny() operation – examples

Example 1

Find any number in the non-parallel stream:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(3, 7, 9, 15, 17));

    Optional<Integer> resultOptional = numbers.stream().findAny();

    if (resultOptional.isPresent()) { // checking if optional contains any value
      System.out.println("The element returned from the stream: " + resultOptional.get()); // getting the value from Optional
    } else {
      System.out.println("The stream is empty.");
    }
  }
}

Output: The element returned from the stream: 3


Example 2
Find any number in the parallel stream:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(3, 7, 9, 15, 17));

    Optional<Integer> resultOptional = numbers.parallelStream().findAny();

    if (resultOptional.isPresent()) { // checking if optional contains any value
      System.out.println("The element returned from the stream: " + resultOptional.get()); // getting the value from Optional
    } else {
      System.out.println("The stream is empty.");
    }
  }
}

Output: The element returned from the stream: 9


Here, the output is 9. However, if we run the program a couple of more times, there is no guarantee that the output will always be the same because as soon as one of the threads from the parallel stream finds any element, the flow will stop, and that element will be present in the Optional.

That’s it!

 

Leave a Reply

Your email address will not be published.