Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
Stream terminal operations for the OCP 21 exam: count, min and max with a Comparator, findFirst and findAny, anyMatch, allMatch and noneMatch, forEach, the three reduce signatures, collect with a supplier, accumulator and combiner, toList and toArray, and which ones finish on infinite streams.
kvi5hnuCode Sprout team member8 min readOn this page
A terminal operation ends a pipeline. It starts the processing, produces the final result, and uses up the stream. A pipeline can have no intermediate operations at all, but it always needs exactly one terminal operation. That's why terminal operations come first in this chapter.
A reduction is a terminal operation that combines all elements into one result, whether a number, an object or a collection. Operations that can stop early, such as findFirst and anyMatch, aren't reductions.

count
long count()
count() returns a long, so int n = stream.count(); doesn't compile without a cast. It's a reduction, so it never ends on an infinite stream.
min and max
Optional<T> min(Comparator<? super T> comparator)
Optional<T> max(Comparator<? super T> comparator)
On a Stream<T>, both methods require a Comparator, so stream.min() doesn't compile. The no-argument min() belongs to primitive streams (article 64). Both return an Optional, which is empty when the stream is empty:
Stream.of("kiwi", "fig", "banana").min(Comparator.comparingInt(String::length)); // Optional[fig]
Stream.<String>empty().max(Comparator.naturalOrder()); // Optional.empty
A stream supports only one terminal operation, so you can't get both the minimum and the maximum from the same stream. Use two streams, or summaryStatistics() on a primitive stream.
findFirst and findAny
Optional<T> findFirst()
Optional<T> findAny()
Both return an element wrapped in an Optional, or Optional.empty() for an empty stream. They're short-circuiting: they stop as soon as they have an element, so they can finish even on infinite streams (as soon as one element reaches them; not if an upstream filter rejects everything).
findFirst()always returns the first element in encounter order, even on a parallel stream.findAny()may return any element. On a sequential stream it usually returns the first one, but that isn't guaranteed. On a parallel stream, the result really can vary. On the exam, "findAnyprints the first element" is right only with the word "usually".
anyMatch, allMatch, noneMatch
boolean anyMatch(Predicate<? super T> p)
boolean allMatch(Predicate<? super T> p)
boolean noneMatch(Predicate<? super T> p)
They return a plain boolean, not an Optional, and stop as soon as the answer is known:
| Method | Stops early when it finds… | On an empty stream |
|---|---|---|
anyMatch | a match → true | false |
allMatch | a non-match → false | true |
noneMatch | a match → false | true |
On an infinite stream, these finish only if the deciding element shows up. Stream.iterate(1, n -> n + 1).anyMatch(n -> n == 5) returns true. But allMatch(n -> n > 0) on the same stream never returns, because every element matches and the end never arrives.
forEach
void forEach(Consumer<? super T> action)
forEach (like forEachOrdered) returns void, so var x = stream.forEach(...) doesn't compile. It's meant for side effects such as printing. Two more things to know:
- A
Streamisn'tIterable, sofor (String s : stream)doesn't compile. - On a parallel stream,
forEachdoesn't guarantee order.forEachOrderedprocesses elements in encounter order.
Before you reach for forEach to fill a collection or count something, check whether collect, count or filter would express it directly.
reduce: three signatures
T reduce(T identity, BinaryOperator<T> accumulator)
Optional<T> reduce(BinaryOperator<T> accumulator)
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
1. With an identity. The identity is the starting value, and it's also the result for an empty stream. The return type is T, not an Optional:
Stream.of(3, 5, 6).reduce(1, (a, b) -> a * b); // 90
Stream.<Integer>empty().reduce(1, (a, b) -> a * b); // 1 (the identity)
Stream.of("w", "o", "l", "f").reduce("", String::concat); // "wolf"
2. Without an identity. This returns an Optional<T>. The result is empty if the stream is empty, holds the only element if there's one, and otherwise holds the combined result:
BinaryOperator<Integer> multiply = (a, b) -> a * b;
Stream.<Integer>empty().reduce(multiply); // Optional.empty
Stream.of(7).reduce(multiply); // Optional[7]: the accumulator never runs
Stream.of(2, 3, 7).reduce(multiply); // Optional[42]
The Optional lets you tell "no data" apart from "a result that happens to equal the identity".
3. With an identity, an accumulator and a combiner. Use this when the result type differs from the element type. The accumulator folds a T into a U, and the combiner merges two partial U results. Parallel streams need that step, because they reduce chunks separately:
int letters = Stream.of("ab", "c", "def").reduce(0, (sum, s) -> sum + s.length(), Integer::sum); // 6
Without the combiner, reduce(0, (sum, s) -> sum + s.length()) doesn't compile: the two-argument form needs a BinaryOperator<T>, and (Integer, String) -> Integer isn't one.
For reduce to work correctly, especially in parallel, the identity must really be neutral (0 for addition, 1 for multiplication, "" for concatenation), and the accumulator must be associative. Subtraction isn't: Stream.of(1, 2, 3, 4).reduce(0, (a, b) -> a - b) gives -10 sequentially, but parallel runs can produce other values.
collect
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
<R, A> R collect(Collector<? super T, A, R> collector)
collect is a mutable reduction. Instead of creating a new value at each step, as reduce does with immutable values, it adds each element into one mutable container, such as a StringBuilder, an ArrayList or a TreeSet. That's more efficient for building collections and strings.
The three-function form spells out each step:
StringBuilder word = Stream.of("w", "o", "l", "f")
.collect(StringBuilder::new, // supplier: create the empty container
StringBuilder::append, // accumulator: add one element
StringBuilder::append); // combiner: merge two containers (parallel)
TreeSet<String> set = Stream.of("w", "o", "l", "f")
.collect(TreeSet::new, TreeSet::add, TreeSet::addAll); // [f, l, o, w]
The accumulator and combiner are BiConsumers: they change the container and return nothing. For a TreeSet, the accumulator adds one element (add) and the combiner merges two sets (addAll).
The second form takes a ready-made Collector. The Collectors class provides dozens of them, which article 65 covers in depth:
Set<String> sorted = stream.collect(Collectors.toCollection(TreeSet::new));
Set<String> any = stream.collect(Collectors.toSet()); // no guarantee which Set class
String csv = stream.collect(Collectors.joining(", "));
toList and toArray
| Call | Result |
|---|---|
stream.toList() (Java 16) | an unmodifiable List. Allows null elements |
stream.collect(Collectors.toList()) | a List with no guarantees about type or mutability. In practice it's a modifiable ArrayList |
stream.collect(Collectors.toUnmodifiableList()) (Java 10) | unmodifiable, and rejects null |
stream.toArray() | Object[], so String[] a = stream.toArray(); doesn't compile |
stream.toArray(String[]::new) | a typed array |
stream.toList() is the modern default when you just want the elements. Calling add on its result throws UnsupportedOperationException.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
Stream.toList()(Java 16) returns an unmodifiable list and is the shortest way to collect to a list.- Java 24 finalized stream gatherers (
Stream.gather, JEP 485), the custom intermediate counterpart tocollect. They're on the Java 25 exam only (article 61).
Exam traps from this article
A complete example
The program runs every terminal operation on a small list of Order records: count, min/max, findFirst, the three match methods (including the empty-stream case), all three forms of reduce, both forms of collect, toList, toArray and forEach.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Solution {
record Order(String customer, int items, double total) {}
static final List<Order> ORDERS = List.of(
new Order("Ines", 3, 42.50),
new Order("Omar", 1, 9.99),
new Order("Ines", 5, 120.00),
new Order("Yuki", 2, 18.25));
public static void main(String[] args) {
// count: a long
long bigOrders = ORDERS.stream().filter(o -> o.items() >= 3).count();
System.out.println("orders with 3+ items: " + bigOrders);
// min / max need a Comparator and return Optional
Optional<Order> cheapest = ORDERS.stream().min(Comparator.comparingDouble(Order::total));
Optional<Order> none = Stream.<Order>empty().max(Comparator.comparingDouble(Order::total));
System.out.println("cheapest: " + cheapest.map(Order::customer).orElse("?")
+ ", max of empty: " + none);
// findFirst / findAny return Optional; they stop early
System.out.println("first Ines order: "
+ ORDERS.stream().filter(o -> o.customer().equals("Ines")).findFirst().map(Order::total).orElse(0.0));
// anyMatch / allMatch / noneMatch return boolean; note the empty-stream answers
System.out.println("any over 100? " + ORDERS.stream().anyMatch(o -> o.total() > 100)
+ ", all non-empty? " + ORDERS.stream().allMatch(o -> o.items() > 0)
+ ", none by Zed? " + ORDERS.stream().noneMatch(o -> o.customer().equals("Zed"))
+ ", allMatch on empty: " + Stream.<Order>empty().allMatch(o -> false));
// reduce, form 1: identity + accumulator -> T
int totalItems = ORDERS.stream().map(Order::items).reduce(0, Integer::sum);
// reduce, form 2: accumulator only -> Optional<T>
BinaryOperator<Integer> multiply = (a, b) -> a * b;
Optional<Integer> product = Stream.of(2, 3, 7).reduce(multiply);
Optional<Integer> emptyProduct = Stream.<Integer>empty().reduce(multiply);
// reduce, form 3: identity + accumulator of a different type + combiner
int nameLetters = ORDERS.stream().reduce(0, (sum, o) -> sum + o.customer().length(), Integer::sum);
System.out.println("reduce: items " + totalItems + ", product " + product + ", empty " + emptyProduct
+ ", letters " + nameLetters);
// collect, the three-function form
StringBuilder initials = ORDERS.stream()
.map(o -> o.customer().substring(0, 1))
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);
TreeSet<String> customers = ORDERS.stream()
.map(Order::customer)
.collect(TreeSet::new, TreeSet::add, TreeSet::addAll);
// collect with a ready-made Collector
Set<String> sameAgain = ORDERS.stream().map(Order::customer).collect(Collectors.toCollection(TreeSet::new));
String joined = ORDERS.stream().map(Order::customer).distinct().collect(Collectors.joining(" & "));
System.out.println("collect: " + initials + " " + customers + " " + sameAgain + " " + joined);
// toList (Java 16) is unmodifiable; toArray needs a generator to get a typed array
List<Double> totals = ORDERS.stream().map(Order::total).toList();
String[] names = ORDERS.stream().map(Order::customer).toArray(String[]::new);
try {
totals.add(1.0);
} catch (UnsupportedOperationException e) {
System.out.println("toList() result is unmodifiable: " + totals);
}
System.out.println("toArray: " + Arrays.toString(names));
// forEach returns void; it's for side effects
ORDERS.stream().filter(o -> o.total() < 20).forEach(o -> System.out.println("small order: " + o));
}
}
Output:
orders with 3+ items: 2
cheapest: Omar, max of empty: Optional.empty
first Ines order: 42.5
any over 100? true, all non-empty? true, none by Zed? true, allMatch on empty: true
reduce: items 11, product Optional[42], empty Optional.empty, letters 16
collect: IOIY [Ines, Omar, Yuki] [Ines, Omar, Yuki] Ines & Omar & Yuki
toList() result is unmodifiable: [42.5, 9.99, 120.0, 18.25]
toArray: [Ines, Omar, Ines, Yuki]
small order: Order[customer=Omar, items=1, total=9.99]
small order: Order[customer=Yuki, items=2, total=18.25]
Points to notice:
maxon an empty stream returnedOptional.empty, andallMatchon an empty stream returnedtrue.reduce(0, Integer::sum)returned a plainint, whilereduce(multiply)returned anOptional, which was empty for the empty stream.- The three-argument
reducesummedStringlengths into anint. That needs a combiner, because the element and result types differ. - Both
collectforms produced the same sortedTreeSet. toList()refusedadd, whiletoArray(String[]::new)gave a realString[].
Common questions
reduce or collect: which should I use?
Use reduce for immutable results such as sums, products, maximums or concatenating a few strings. Use collect to build a collection or a long string, because it mutates one container instead of creating many intermediate objects.
Why does toList() allow nulls but toUnmodifiableList() doesn't?
toUnmodifiableList() follows the List.of rules, which forbid null. toList() was added later for convenience, and it simply wraps whatever the stream produced.
Is stream().forEach slower than a loop?
For small collections, the difference doesn't matter. Choose whichever reads better. Streams pay off with longer pipelines.
Summary
countreturns along,min/maxtake aComparatorand returnOptional, andfindFirst/findAnyreturnOptionaland short-circuit.anyMatch,allMatchandnoneMatchreturnboolean, short-circuit, and have fixed answers for empty streams.forEachreturnsvoidand is for side effects.reducehas three forms: with an identity (T), without one (Optional<T>), and with a combiner for a different result type (U).collectis a mutable reduction: either a supplier, an accumulator and a combiner, or aCollector.toList()gives an unmodifiable list, andtoArray(String[]::new)a typed array.
Practice quiz
Test yourself with the terminal operations quiz: 10 exam-style questions with explanations.
Previous: Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
Next: Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)
Related reading
- Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)
- Java Optional: Creating, Checking and Unwrapping Optional Values (OCP 21)
- Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
- Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
- Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.