Java Stream Reductions: count, max, min, findFirst, findAny and anyMatch
Get answers out of Java streams with the simple terminal reductions count, max, min, findFirst, findAny, anyMatch, allMatch and noneMatch. Learn why they return Optional, how short-circuiting works, the empty-stream rules and when findAny beats findFirst.
kvi5hnuCode Sprout team member8 min readOn this page
You now know how to create streams and transform them. The point of all that is to get answers out of the data. Terminal operations that boil a stream down to a single non-stream value are called reductions. This article covers the simple ones: counting, finding the largest or smallest element, finding a matching element, and testing whether elements match a condition. Later articles cover collecting into collections and maps (article 8 onward) and general reduce (article 13).
count, max and min
You've already met count(), which returns the number of elements as a long.
max and min return the largest and smallest element according to a Comparator. There is a twist: they don't return a T, they return an Optional<T>. If the stream is empty, there is no largest element, and instead of returning null, which tends to cause a NullPointerException somewhere far away in an untested code path, the result is an empty Optional:
Optional<String> largest = words.max(String::compareToIgnoreCase);
System.out.println("largest: " + largest.orElse(""));
orElse("") unwraps the value, or supplies a default if there is none. The next two articles cover Optional in depth.
Since max and min need a comparator, the comparator factory methods from the first course do the heavy lifting:
words.min(Comparator.comparing(String::length)) // a shortest word
words.max(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
numbers.max(Comparator.naturalOrder()) // natural order of Comparable elements
When several elements tie for the maximum or minimum, which one you get isn't specified. To get a predictable result, break ties explicitly with thenComparing, as in the second line above. For primitive streams, IntStream.max() needs no comparator and returns an OptionalInt (article 16).
findFirst and findAny
findFirst() returns the first element of the stream in encounter order, wrapped in an Optional, or an empty Optional if the stream is empty. On its own that's rarely useful, but combined with filter it answers "find the first element that…":
Optional<String> startsWithQ = words.filter(s -> s.startsWith("Q")).findFirst();
Thanks to laziness, this doesn't filter the whole stream. Elements flow through filter one at a time, and as soon as the first match reaches findFirst, the pipeline stops. It works even on infinite streams.
If any match will do, not necessarily the first one, use findAny(). On a sequential stream it usually returns the first element anyway, but you mustn't rely on that. On a parallel stream it really pays off: each thread can report whatever match it finds first, instead of coordinating with the others to determine which match comes earliest in the stream.
Optional<String> startsWithQ = words.parallel().filter(s -> s.startsWith("Q")).findAny();
The flip side: findAny on a parallel stream can return a different element from run to run.
anyMatch, allMatch and noneMatch
If you only want to know whether there's a match, use anyMatch with a predicate. It returns a plain boolean:
boolean aWordStartsWithQ = words.anyMatch(s -> s.startsWith("Q"));
allMatch returns true if every element matches, and noneMatch returns true if no element matches. All three are short-circuiting. anyMatch stops at the first match, while allMatch and noneMatch stop at the first element that decides the answer. In the demo, anyMatch(s -> s.startsWith("b")) visits only three words before it finds "beginning". They work well in parallel too, since any thread that finds a deciding element can stop the others.
The empty-stream rules
What should allMatch return for an empty stream? Mathematics gives the answer: a statement about all members of an empty set is vacuously true. So:
| On an empty stream | Result |
|---|---|
anyMatch(p) | false: there's no element that matches |
allMatch(p) | true: there's no element that fails |
noneMatch(p) | true: there's no element that matches |
This can surprise you in validation code. "All items in the cart are in stock" is true for an empty cart, so check for emptiness separately if an empty input should be an error.
Infinite streams and reductions
Some reductions need to see every element: count, max and min never finish on an infinite stream. The short-circuiting ones (findFirst, findAny, anyMatch, and allMatch or noneMatch once a deciding element shows up) can finish, as long as a matching element eventually appears:
int firstBigSquare = Stream.iterate(1, n -> n + 1).map(n -> n * n).filter(n -> n > 500).findFirst().orElseThrow();
If no element ever matches, these run forever as well.
A complete example
import java.util.*;
import java.util.stream.*;
public class Solution {
public static void main(String[] args) {
List<String> words = List.of("Alice", "was", "beginning", "to", "get", "very",
"tired", "of", "sitting", "by", "her", "sister", "Queen", "quietly");
// count, max, min
System.out.println("count: " + words.stream().count());
Optional<String> largest = words.stream().max(String::compareToIgnoreCase);
System.out.println("largest: " + largest.orElse(""));
Optional<String> shortest = words.stream().min(Comparator.comparing(String::length));
System.out.println("shortest: " + shortest.orElse(""));
Optional<String> longest = words.stream().max(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println("longest: " + longest.orElse(""));
// empty streams give empty optionals instead of null
Optional<String> none = Stream.<String>empty().max(Comparator.naturalOrder());
System.out.println("max of empty stream: " + none);
// findFirst with filter
Optional<String> startsWithQ = words.stream().filter(s -> s.startsWith("Q")).findFirst();
System.out.println("first word starting with Q: " + startsWithQ.orElse("(none)"));
Optional<String> startsWithZ = words.stream().filter(s -> s.startsWith("Z")).findFirst();
System.out.println("first word starting with Z: " + startsWithZ.orElse("(none)"));
// findAny: any match is fine, useful in parallel
Optional<String> anyQ = words.parallelStream().filter(s -> s.toLowerCase().startsWith("q")).findAny();
System.out.println("some word starting with q or Q is present: " + anyQ.isPresent());
// anyMatch, allMatch, noneMatch
System.out.println("anyMatch length > 8: " + words.stream().anyMatch(s -> s.length() > 8));
System.out.println("allMatch is lowercase: " + words.stream().allMatch(s -> s.equals(s.toLowerCase())));
System.out.println("noneMatch is empty: " + words.stream().noneMatch(String::isEmpty));
// the empty-stream rules
Stream<String> empty1 = Stream.empty(), empty2 = Stream.empty(), empty3 = Stream.empty();
System.out.println("empty: anyMatch=" + empty1.anyMatch(s -> true)
+ ", allMatch=" + empty2.allMatch(s -> false)
+ ", noneMatch=" + empty3.noneMatch(s -> true));
// short-circuiting: anyMatch stops at the first hit
var visited = new ArrayList<String>();
boolean found = words.stream().peek(visited::add).anyMatch(s -> s.startsWith("b"));
System.out.println("anyMatch found " + found + " after visiting " + visited);
// findFirst can't wrap a null element
try {
Stream.of(null, "x").findFirst();
} catch (NullPointerException e) {
System.out.println("findFirst on a null element: NullPointerException");
}
// max on infinite streams never ends; findFirst is fine
System.out.println("first square above 500: "
+ Stream.iterate(1, n -> n + 1).map(n -> n * n).filter(n -> n > 500).findFirst().orElseThrow());
}
}
count: 14
largest: was
shortest: to
longest: beginning
max of empty stream: Optional.empty
first word starting with Q: Queen
first word starting with Z: (none)
some word starting with q or Q is present: true
anyMatch length > 8: true
allMatch is lowercase: false
noneMatch is empty: true
empty: anyMatch=false, allMatch=true, noneMatch=true
anyMatch found true after visiting [Alice, was, beginning]
findFirst on a null element: NullPointerException
first square above 500: 529
String::compareToIgnoreCase ranks "was" highest because w comes last in the alphabet among the first letters. The parallel findAny result isn't printed directly because it may vary between runs. Only its presence is.
Common questions
How do I find the index of the first element that matches?
Streams of objects have no indexes, but you can stream the indexes of a list or array: IntStream.range(0, list.size()).filter(i -> list.get(i).startsWith("b")).findFirst() returns an OptionalInt. For a List, a plain indexOf or a loop also works.
How do I get the minimum and the maximum in one pass?
For numbers, use summary statistics: mapToInt(String::length).summaryStatistics() gives count, sum, min, average and max at once (article 8). For objects compared with a comparator, use the teeing collector with minBy and maxBy (article 11).
Why does count() return a long and not an int?
Streams are not limited by the size of a collection; a generated or file-based stream can have more than Integer.MAX_VALUE elements. Convert with Math.toIntExact(count) if you need an int and want an exception rather than silent overflow.
I know the stream is not empty. Why do I still get an Optional from max?
The type system cannot know that. Unwrap with orElseThrow(), which documents your assumption and fails loudly if it is ever wrong.
Is anyMatch faster than filter(...).findFirst().isPresent()?
Both short-circuit and do about the same work. anyMatch states the intent directly and returns a boolean, so prefer it.
Is stream.count() the same as list.size()?
It gives the same number for an unfiltered list's stream, and since Java 9 it even skips the traversal in that case. But list.size() is clearer. Use count() when there is a pipeline in front of it.
API reference
java.util.stream.Stream<T> (all terminal operations)
| Method | Description |
|---|---|
long count() | the number of elements |
Optional<T> max(Comparator<? super T> comparator), Optional<T> min(Comparator<? super T> comparator) | a largest or smallest element, or an empty Optional for an empty stream |
Optional<T> findFirst() | the first element in encounter order, or an empty Optional (short-circuiting) |
Optional<T> findAny() | some element, or an empty Optional; free to pick any in parallel streams (short-circuiting) |
boolean anyMatch(Predicate<? super T> predicate) | true if some element matches; false for an empty stream |
boolean allMatch(Predicate<? super T> predicate) | true if every element matches; true for an empty stream |
boolean noneMatch(Predicate<? super T> predicate) | true if no element matches; true for an empty stream |
Summary
- Reductions are terminal operations that produce a single value from a stream.
max,min,findFirstandfindAnyreturn anOptional, which is empty when there's no answer. They throwNullPointerExceptionif the chosen element isnull.findFirstrespects encounter order.findAnymay return any match, which is faster in parallel but not deterministic.anyMatch,allMatchandnoneMatchreturn abooleanand short-circuit. On an empty stream,allMatchandnoneMatcharetrueandanyMatchisfalse.count,maxandminmust see every element, so they never finish on infinite streams.
Practice Questions
Why does Stream.max return Optional<T> instead of T?
Because an empty stream has no maximum. Returning null would push a hidden NullPointerException risk to the caller. An empty Optional makes the "no result" case explicit, and the caller handles it with methods like orElse.
What do Stream.empty().allMatch(x -> false) and Stream.empty().anyMatch(x -> true) return?
true and false. allMatch is vacuously true on an empty stream because no element fails the predicate. anyMatch is false because there's no element that could match.
When should you prefer findAny over findFirst?
When any matching element is acceptable and the stream may run in parallel. findAny lets each thread return the first match it sees, without coordinating to find the earliest in encounter order. If you need a deterministic result, use findFirst.
Write an expression that tells whether a List<String> names contains a name longer than 20 characters, stopping as soon as one is found.
names.stream().anyMatch(n -> n.length() > 20). anyMatch short-circuits at the first matching element.
Two employees share the highest salary. Which one does employees.stream().max(Comparator.comparing(Employee::salary)) return, and how do you make the answer predictable?
The specification doesn't say which of the tied elements is returned. Add a tie-breaker to the comparator, for example Comparator.comparing(Employee::salary).thenComparing(Employee::name), so the comparator never reports a tie between different employees.
Previous: Java Stream limit, skip, takeWhile, concat, distinct, sorted and peek
Next: Java Optional: Getting, Consuming and Transforming Optional Values
Related reading
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.