Java Stream findAny: Usage and Performance
Learn how to use Java Stream findAny() correctly, including its behavior on parallel streams and when to prefer it over findFirst().

The findAny() method on a Java Stream returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. It is a short-circuiting terminal operation, so it can stop processing as soon as an element is found. That makes it useful when you only need one matching element and do not care which one. The method is part of the java.util.stream.Stream interface and has been available since Java 8.
Basic Usage of findAny()
Using findAny() is straightforward. You call it on a stream, optionally after applying intermediate operations like filter() or map(), and it returns an Optional<T>. The examples in this article use modern Java syntax such as List.of() and records; findAny() and the stream operations shown have been available since Java 8.
List<String> names = List.of("Alice", "Bob", "Charlie");
Optional<String> anyName = names.stream().findAny();
anyName.ifPresent(System.out::println);The result is not guaranteed to be a specific element. In a sequential stream, it will typically be the first element in the stream, but relying on that is a mistake. The contract of findAny() explicitly allows any element, and the implementation may choose an element based on internal optimizations. When the stream is parallel, the result can be nondeterministic.
A more practical use is to find an element that matches a condition without caring which one. For instance, you might want any available user with an admin role:
List<User> users = getUsers();
Optional<User> anyAdmin = users.stream()
.filter(User::isAdmin)
.findAny();If at least one admin exists, anyAdmin will contain one of them. If none exist, it will be empty.
findAny() vs findFirst()
The most common confusion is between findAny() and findFirst(). Both return an Optional describing an element of the stream, but they differ in the guarantee they provide:
| Method | Guarantee | Best suited for |
|---|---|---|
findAny() | Returns any element, no order guarantee | Parallel streams, when order is irrelevant |
findFirst() | Returns the first element in encounter order for ordered streams | Streams where order matters |
For streams without a defined encounter order, findFirst() may return an arbitrary element, just like findAny().
In a sequential stream that has a defined encounter order, findFirst() always returns the first element that matches the stream's encounter order. findAny() may also return the first element, but it is not required to do so. The difference becomes significant when the stream is parallel. findFirst() must preserve encounter order, which can require additional synchronization and reduce parallelism. findAny() can return the first element found by any thread, which often improves parallel performance.
Choose findFirst() when you need the first matching element according to the stream's defined order. Choose findAny() when any matching element is acceptable, especially in parallel processing.
Behavior on Parallel Streams
Parallel streams split the source data into substreams processed by multiple threads. The findAny() operation is designed to return an element from whichever thread finds a result first. This makes it nondeterministic: the returned element may vary between runs, even with the same input data.
List<Integer> numbers = IntStream.rangeClosed(1, 1_000_000)
.boxed()
.collect(Collectors.toList());
Optional<Integer> any = numbers.parallelStream()
.filter(n -> n % 7 == 0)
.findAny();Running this code multiple times can yield different multiples of 7. That is not a bug; it is the intended behavior of findAny(). If your logic depends on a specific element, use findFirst() instead. If you only need to retrieve one matching element and any one will do, findAny() is sufficient and often faster in parallel scenarios.
It is worth noting that findAny() is not guaranteed to be the first element even in a sequential stream. The Java API documentation states that it may return any element, and the implementation is free to choose one. In practice, sequential streams often return the first element, but you should not rely on that behavior.
Performance and Short-Circuiting
findAny() is a short-circuiting terminal operation. This means it does not necessarily process the entire stream. As soon as an element is found, the operation terminates, and the stream pipeline stops processing further elements. This can lead to significant performance gains when working with large streams or expensive intermediate operations.
For example, consider a stream that applies a costly transformation to each element:
Optional<String> result = data.stream()
.map(this::expensiveTransformation)
.filter(s -> s.startsWith("target"))
.findAny();In a sequential stream, if a matching element appears early, findAny() stops the pipeline, and the map operation is not applied to elements after that point. This is different from a non-short-circuiting operation like collect(), which processes all elements.
In parallel streams, short-circuiting also helps with performance because threads can stop once a result is found, reducing wasted work. However, the exact performance benefit depends on the source and the number of threads. Do not assume a specific speedup without measuring.
One caveat: if the stream is infinite, findAny() will never terminate if no element matches. It will keep generating elements indefinitely. This is a common pitfall, discussed next.
Common Pitfalls with findAny()
Several mistakes can lead to bugs or unexpected behavior when using findAny().
Empty Stream
If the stream is empty, findAny() returns an empty Optional. Trying to call get() on that Optional throws NoSuchElementException. Always use ifPresent(), orElse(), or orElseThrow() to handle the empty case safely.
List<String> emptyList = List.of();
Optional<String> result = emptyList.stream().findAny();
String value = result.orElse("default");Infinite Streams
As mentioned, findAny() on an infinite stream will only terminate if a matching element is found. If the filter never matches, the operation runs forever. This is especially dangerous with iterate() or generate(). Always ensure that the stream is finite or that the filter will eventually match.
// Don't run this: the predicate never matches, so findAny() never terminates
Stream.iterate(1, n -> n + 1)
.filter(n -> n < 0)
.findAny();Null Elements
findAny() returns an Optional, and Optional cannot contain null. If findAny() selects a null element, the operation can throw NullPointerException when the Optional is created. Avoid null values in streams, or filter them out before calling findAny().
Relying on Order
Even in a sequential stream, do not assume findAny() returns the first element. If order matters, use findFirst(). This is a subtle but important distinction that can cause intermittent bugs in production.
When to Use findAny() vs Other Terminal Operations
findAny() is not always the right choice. It is best suited for scenarios where you need to retrieve one matching element without caring which one. If you only need to check existence, anyMatch() is more direct and returns a boolean. If you need to collect all matching elements, use filter().collect(). If you need to reduce the stream to a single value, use reduce().
Here is a quick decision guide:
| Need | Operation to use |
|---|---|
| Get any matching element, order irrelevant | findAny() |
| Get the first matching element | findFirst() |
| Check if any element matches | anyMatch() |
| Get all matching elements | filter().collect(Collectors.toList()) |
| Combine elements into a single value | reduce() |
Using findAny() when you actually need the first element is a common mistake. Similarly, using anyMatch() when you need the element itself often forces a second stream traversal. Choose the operation that matches the semantic requirement.
In parallel streams, findAny() often outperforms findFirst() because it does not need to coordinate encounter order. If your application does not depend on which element is returned, prefer findAny() for better parallel performance. For sequential streams, the performance difference is negligible, so correctness and readability should decide.
Practical Example: Filtering and Finding an Element
Consider a scenario where you have a list of orders and you need to find any order that is both urgent and assigned to a specific customer. Since you only need one such order, findAny() is appropriate:
record Order(String id, String customerId, boolean urgent, boolean assigned) {}
List<Order> orders = getOrders();
Optional<Order> urgentOrder = orders.stream()
.filter(o -> o.urgent())
.filter(o -> o.customerId().equals("cust-123"))
.findAny();
urgentOrder.ifPresent(order -> sendNotification(order));This code stops as soon as an order matching both conditions is found. If the list is large and the matching order appears early, the pipeline avoids processing the rest. The Optional is handled safely with ifPresent.
When working with parallel streams, the same code works, but the returned order may differ between runs. If that is acceptable, findAny() is the right tool. If the order matters, replace it with findFirst().
Understanding the contract of findAny()—that it returns an arbitrary element—is essential for writing correct, maintainable code. It is a simple method, but its behavior in parallel streams and its short-circuiting nature have real implications for performance and correctness.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.