Java 8 Stream findFirst() vs. findAny()

1. Overview

The Java 8 Stream API introduced two methods that are often misunderstood: findAny() and findFirst().

In this quick tutorial, we’ll look at the difference between these two methods and when to use them.

2. Using Stream.findAny()

As the name suggests, the findAny() method allows us to find any element from a Stream. We use it when we’re looking for an element without paying an attention to the encounter order:

The method returns an Optional instance, which is empty if the Stream is empty:

@Test
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
    List<String> list = Arrays.asList("A","B","C","D");

    Optional<String> result = list.stream().findAny();

    assertTrue(result.isPresent());
    assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
}

In a non-parallel operation, it will most likely return the first element in the Stream, but there is no guarantee for this.

For maximum performance when processing the parallel operation, the result cannot be reliably determined:

@Test
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect()() {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    Optional<Integer> result = list
      .stream().parallel()
      .filter(num -> num < 4).findAny();

    assertTrue(result.isPresent());
    assertThat(result.get(), anyOf(is(1), is(2), is(3)));
}

3. Using Stream.findFirst()

The findFirst() method finds the first element in a Stream. So, we use this method when we specifically want the first element from a sequence.

When there is no encounter order, it returns any element from the Stream. According to the java.util.streams package documentation, “Streams may or may not have a defined encounter order. It depends on the source and the intermediate operations.”

The return type is also an Optional instance, which is empty if the Stream is empty too:

@Test
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {

    List<String> list = Arrays.asList("A", "B", "C", "D");

    Optional<String> result = list.stream().findFirst();

    assertTrue(result.isPresent());
    assertThat(result.get(), is("A"));
}

The behavior of the findFirst method does not change in the parallel scenario. If the encounter order exists, it will always behave deterministically.

4. Conclusion

In this article, we looked at the findAny() and findFirst() methods of the Java 8 Streams API.

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

The complete source code and all code snippets for this article are over on GitHub.

Related posts:

Testing an OAuth Secured API with Spring MVC
Java Program to Represent Graph Using Incidence Matrix
Java Program to Implement Booth Algorithm
Java Program to Represent Graph Using Linked List
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
How To Serialize and Deserialize Enums with Jackson
Java Program to Perform String Matching Using String Library
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Custom Cascading in Spring Data MongoDB
Guide to the Synchronized Keyword in Java
Control Structures in Java
Queue và PriorityQueue trong Java
Java Program to Implement a Binary Search Tree using Linked Lists
Java Program to Create a Balanced Binary Tree of the Incoming Data
Java Program to Find Transpose of a Graph Matrix
Zipping Collections in Java
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Java Program to Describe the Representation of Graph using Adjacency List
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Spring Security Registration – Resend Verification Email
Java Program to Implement DelayQueue API
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Checking for Empty or Blank Strings in Java
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Request a Delivery / Read Receipt in Javamail
Java Program to Represent Graph Using Adjacency List
How to Set TLS Version in Apache HttpClient
“Stream has already been operated upon or closed” Exception in Java
Guide to Java 8’s Collectors
Sắp xếp trong Java 8
Java Program to do a Depth First Search/Traversal on a graph non-recursively