Course contentsShow
← Java
Lesson 1543 of 2,87033. Streams API: Terminal OperationsFree lesson

findAny: Non-Deterministic Selection for Performance

Understand findAny's flexibility in parallel streams, allowing any element to be returned for better performance.

findAny: Non-Deterministic Selection for Performance

What you'll learn: How findAny() trades determinism for speed, especially in parallel streams where any matching element is acceptable.

Why findAny Exists

While findFirst() always returns the first element encountered, findAny() gives the stream implementation freedom to return any element from the stream. This seemingly small difference becomes powerful when performance matters.

The Core Idea

Think of findFirst() as standing in line at a ticket booth—you must serve the first person. But findAny() is like having multiple cashiers where anyone available can be served first. When you don't care about which element you get, why force the stream to coordinate finding the first one?

Where findAny Shines

In sequential streams, findAny() typically behaves identically to findFirst()—it returns the first element encountered. But in parallel streams, findAny() allows whichever thread finishes processing a matching element first to return immediately, without waiting for other threads or checking position order.

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Sequential: typically returns first match (2)
Optional<Integer> anySeq = numbers.stream()
    .filter(n -> n % 2 == 0)
    .findAny();

// Parallel: returns ANY even number found first
Optional<Integer> anyPar = numbers.parallelStream()
    .filter(n -> n % 2 == 0)
    .findAny();  // might be 2, 4, 6, 8, or 10!

When to Use findAny

Use findAny() when:

  • You need a match, not the first match
  • Performance is critical with parallel streams
  • Order doesn't matter for your logic

Key Takeaway: findAny() sacrifices determinism for performance, allowing parallel streams to return any matching element without coordinating across threads—perfect when you only care that something matches, not what matches.