for loop with a temporary list or map beside it. The Stream API lets you write the same thing as a pipeline that says what you want, and this post teaches it from the first filter to the Collectors recipes you will use every week, plus the traps that make a stream quietly behave differently from the loop it replaced.
You do not need to know lambdas perfectly, but you do need to read n -> n * 2 without panic. If Function and Predicate are unfamiliar, read Java Functional Interfaces: Function, Predicate, Supplier and Consumer Explained first; it shows which interface each stream method expects. The sections run in difficulty order, each opens with the plain-language version, and the collapsible “going deeper” panels hold the intermediate and reference-level material, so you can read straight through and open them later. This page replaces two older ankurm.com posts (the streams reference guide and the Collectors cookbook) and keeps everything useful from both. Every output block is quoted from a run whose output is committed to the companion repository, and each code or output block links to the file it came from.
Versions this was built and run against. JDK 25.0.5.1+2 (Temurin, LTS), Maven 3.9.11, JUnit Jupiter 5.11.0.Stream.toList()andmapMultineed Java 16;takeWhile,dropWhile,Collectors.filteringandflatMappingneed Java 9;Collectors.teeingneeds Java 12. Stream Gatherers are final in JDK 24 (JEP 485, after previews in JDK 22 and 23), so they need no--enable-previewflag on JDK 25 — the committedjavapoutput confirms the class is there. The 12 contract tests in the module pin the behaviours claimed below; if the JDK ever changes one, a test fails.
A stream is a description of work, not a container of data
AStream<T> does not hold your elements. It is a recipe that says where the elements come from, what to do to each one, and what to produce at the end. That recipe has exactly three parts: a source (a collection, an array, a generator), zero or more intermediate operations such as filter and map that each return another stream, and one terminal operation such as toList() or count() that produces the answer.
filter or map only extends the recipe. The green box is eager: it is the only thing that makes work happen. Hold on to that sentence, because the next section turns it into something you can watch, and the single worst stream bug later in the post is a consequence of it.
There are many ways to get a source. These are the ones you will actually type, from CreationDemo.java:
List<String> names = List.of("Alice", "Bob", "Carol");
System.out.println("collection.stream() : " + names.stream().toList());
System.out.println("Stream.of(1,2,3) : " + Stream.of(1, 2, 3).toList());
System.out.println("Arrays.stream(array) : " + Arrays.stream(new String[] {"x", "y", "z"}).toList());
System.out.println("IntStream.range(1,6) : " + IntStream.range(1, 6).boxed().toList());
System.out.println("IntStream.rangeClosed : " + IntStream.rangeClosed(1, 5).boxed().toList());
System.out.println("Stream.iterate(0, n+2) : " + Stream.iterate(0, n -> n + 2).limit(5).toList());
// Java 9+: iterate with a hasNext predicate is a stream-shaped for loop.
System.out.println("iterate(1, <100, *3) : " + Stream.iterate(1, n -> n < 100, n -> n * 3).toList());
System.out.println("Stream.generate(...) : " + Stream.generate(() -> "ab").limit(3).toList());
// Java 9+: ofNullable gives an empty stream for null instead of an NPE.
String maybe = null;
System.out.println("Stream.ofNullable(null) : " + Stream.ofNullable(maybe).toList());
System.out.println("Optional.stream() : " + Optional.of("here").stream().toList());
System.out.println("\"a,b,c\".split(\",\") stream : " + Arrays.stream("a,b,c".split(",")).toList());
System.out.println("\"hey\".chars() : " + "hey".chars().boxed().toList());
and this is what they print, quoted from output/01-creation.txt:
collection.stream() : [Alice, Bob, Carol]
Stream.of(1,2,3) : [1, 2, 3]
Arrays.stream(array) : [x, y, z]
IntStream.range(1,6) : [1, 2, 3, 4, 5]
IntStream.rangeClosed : [1, 2, 3, 4, 5]
Stream.iterate(0, n+2) : [0, 2, 4, 6, 8]
iterate(1, <100, *3) : [1, 3, 9, 27, 81]
Stream.generate(...) : [ab, ab, ab]
Stream.ofNullable(null) : []
Optional.stream() : [here]
"a,b,c".split(",") stream : [a, b, c]
"hey".chars() : [104, 101, 121]
Streams are single use. Once a terminal operation has run, that stream object is finished. Using it again throws IllegalStateException; the exact message is in the output of the next section. Keep the source (the list), not the stream, and make a fresh stream each time you need one.
Going deeper: choosing between the creation methods
Usecollection.stream() for anything you already have in a List or Set, and Arrays.stream(array) for arrays. Stream.of(a, b, c) is for a handful of literal values; with a single argument that is itself an array it unpacks the array, which surprises people once. IntStream.range(a, b) excludes b and rangeClosed(a, b) includes it, and both give you a primitive stream so there is no boxing.
Stream.iterate(seed, f) and Stream.generate(supplier) are infinite: they only make sense with a short-circuiting step such as limit, takeWhile or findFirst. Since Java 9 the three-argument iterate(seed, hasNext, next) gives you a finite, loop-shaped stream, and the output above shows [1, 3, 9, 27, 81] for it. Stream.ofNullable(x) turns a possibly-null value into a stream of zero or one element, which is the tidy way to flatten an Optional-like value inside flatMap; Optional.stream() does the same for a real Optional.
Going deeper
- CreationDemo.java — the runnable source for every line above
- Stream (JDK 25 Javadoc) — the factory methods and the pipeline rules
- Java Collections Framework: Choosing the Right Data Structure — where your sources come from
Nothing runs until the terminal operation, and then each element travels the whole pipeline alone
You can prove laziness withpeek, an intermediate operation that hands each element to a callback as it passes. Here is a pipeline that is built but not finished, then finished, from LazyPipelineDemo.java:
Stream<Integer> lazy = List.of(1, 2, 3).stream()
.peek(n -> System.out.println(" peek saw " + n));
System.out.println("pipeline built, nothing printed above this line");
System.out.println("now call toList():");
lazy.toList();
The output is quoted from output/02-lazypipeline.txt. The peek lines appear only after the terminal call:
== 1. Nothing runs until a terminal operation ==
pipeline built, nothing printed above this line
now call toList():
peek saw 1
peek saw 2
peek saw 3
The second consequence of laziness is less obvious. The elements do not go through filter as a batch and then through map as a batch. Each element makes the whole trip before the next one starts:
List.of(1, 2, 3, 4, 5).stream()
.filter(n -> n % 2 != 0)
.peek(n -> System.out.println(" after filter: " + n))
.map(n -> n * n)
.peek(n -> System.out.println(" after map : " + n))
.toList();
== 2. Elements flow one at a time through the whole pipeline ==
after filter: 1
after map : 1
after filter: 3
after map : 9
after filter: 5
after map : 25
map at all. That per-element flow is what lets a short-circuiting operation stop early, which the next block shows. anyMatch found its answer on the third element and the last three were never touched:
int[] touched = {0};
boolean found = Stream.of(5, 8, 12, 3, 9, 20)
.peek(n -> touched[0]++)
.anyMatch(n -> n > 10);
System.out.println("anyMatch(n > 10) = " + found + ", elements touched = " + touched[0] + " of 6");
anyMatch(n > 10) = true, elements touched = 3 of 6
The trap this creates:peekandcount(). In this runcount()printed 3 and not onepeekline. The JDK is allowed to skip the pipeline when it can compute the size from the source, and a plainListsource knows its size. Add afilterand the size becomes unknown, so the samepeeksuddenly fires. A side effect hidden inpeekormaptherefore runs or does not run depending on what else is in the pipeline. The fix is simple: do not put required side effects in intermediate operations.
long n = List.of(1, 2, 3).stream()
.peek(x -> System.out.println(" peek saw " + x))
.count();
System.out.println("count = " + n + " (no peek lines: the size was known from the source)");
long n2 = List.of(1, 2, 3).stream()
.filter(x -> x > 0)
.peek(x -> System.out.println(" peek saw " + x))
.count();
System.out.println("count after filter = " + n2 + " (filter makes the size unknown, so peek runs)");
== 4. count() may skip the pipeline entirely ==
count = 3 (no peek lines: the size was known from the source)
peek saw 1
peek saw 2
peek saw 3
count after filter = 3 (filter makes the size unknown, so peek runs)
The count() behaviour is documented, not an accident: the Stream.count() Javadoc says an implementation may skip executing the pipeline when it can compute the count directly from the source. And here is the single-use rule from the previous section, with the real message:
Stream<String> s = Stream.of("a", "b");
s.toList();
try {
s.toList();
} catch (IllegalStateException e) {
System.out.println("IllegalStateException: " + e.getMessage());
}
== 5. A stream is single use ==
IllegalStateException: stream has already been operated upon or closed
Going deeper: what “lazy” costs and buys you
Because each element makes the whole trip, a pipeline needs no intermediate collections:filter(...).map(...) does not build a filtered list and then a mapped list. That is the real performance benefit of streams over chained loops that each allocate a list, and it is why limit(10) on a huge or infinite source stays cheap.
The exceptions are stateful operations such as sorted() and distinct(). sorted() cannot emit its first element until it has seen the last one, so it acts as a barrier that buffers everything. Put filter and limit before sorted when you can, so the barrier buffers less. The contract tests nothingRunsWithoutTerminalOperation, anyMatchShortCircuits and countSkipsPeekWhenSizeIsKnown in StreamsContractTest.java pin each behaviour in this section as an assertion.
Going deeper
- LazyPipelineDemo.java — all five scenarios, runnable
- output/10-contract-test.txt — 12 of 12 contract tests passing
- Lambda Expressions in Java — why a lambda cannot modify a local variable
The intermediate operations you will use every day
Intermediate operations take a stream and give back a stream, so you chain them. Most days you need four:filter keeps the elements that pass a test, map turns each element into something else, sorted orders them, and distinct removes duplicates (using equals). From IntermediateOpsDemo.java:
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("filter even : " + numbers.stream().filter(n -> n % 2 == 0).toList());
List<String> words = List.of("hello", "world", "java");
System.out.println("map toUpperCase : " + words.stream().map(String::toUpperCase).toList());
filter even : [2, 4, 6, 8, 10]
map toUpperCase : [HELLO, WORLD, JAVA]
The operation that confuses beginners is flatMap. Use map when each element becomes one new element. Use flatMap when each element becomes a stream of new elements and you want one flat result. The first line below keeps the lists as lists of sizes; the second flattens them:
List<List<Integer>> nested = List.of(List.of(1, 2, 3), List.of(4, 5), List.of(6, 7, 8, 9));
System.out.println("map (no flatten) : " + nested.stream().map(List::size).toList() + " <- one result per inner list");
System.out.println("flatMap(List::stream): " + nested.stream().flatMap(List::stream).toList());
map (no flatten) : [3, 2, 4] <- one result per inner list
flatMap(List::stream): [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sorting has one detail worth reading twice: sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())) sorts by length first and alphabetically second, so with Carol, Alice, Bob and Dave the 4-letter Dave comes before the 5-letter Alice:
List<String> names = List.of("Carol", "Alice", "Bob", "Dave");
System.out.println("sorted() : " + names.stream().sorted().toList());
System.out.println("sorted(reverse) : " + names.stream().sorted(Comparator.reverseOrder()).toList());
System.out.println("sorted(len, alpha) : " + names.stream()
.sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())).toList());
sorted() : [Alice, Bob, Carol, Dave]
sorted(reverse) : [Dave, Carol, Bob, Alice]
sorted(len, alpha) : [Bob, Dave, Alice, Carol]
takeWhileis notfilter.filtertests every element.takeWhile(Java 9) stops at the first element that fails and discards everything after it, even elements that would have passed. On[1, 2, 3, 10, 2, 1]with the testn < 5, the output below showstakeWhilegiving[1, 2, 3]andfiltergiving[1, 2, 3, 2, 1]. UsetakeWhileonly on data that is already sorted or grouped so the “first failure” means something.
List<Integer> nums = List.of(1, 2, 2, 3, 3, 3, 4, 5);
System.out.println("distinct() : " + nums.stream().distinct().toList());
System.out.println("limit(4) : " + nums.stream().limit(4).toList());
System.out.println("skip(5) : " + nums.stream().skip(5).toList());
List<Integer> mixed = List.of(1, 2, 3, 10, 2, 1);
System.out.println("takeWhile(< 5) : " + mixed.stream().takeWhile(n -> n < 5).toList());
System.out.println("dropWhile(< 5) : " + mixed.stream().dropWhile(n -> n < 5).toList());
System.out.println("filter(< 5) : " + mixed.stream().filter(n -> n < 5).toList() + " <- not the same thing");
distinct() : [1, 2, 3, 4, 5]
limit(4) : [1, 2, 2, 3]
skip(5) : [3, 4, 5]
takeWhile(< 5) : [1, 2, 3]
dropWhile(< 5) : [10, 2, 1]
filter(< 5) : [1, 2, 3, 2, 1] <- not the same thing
Going deeper: mapMulti, and ordering the operations
mapMulti (Java 16) is flatMap without building a throwaway stream per element: your callback pushes zero, one or many outputs into a sink. It pays off when most elements produce zero or one output. The demo duplicates the even numbers and the output is [1, 2, 2, 3, 4, 4]:
System.out.println("mapMulti (dup evens): " + Stream.of(1, 2, 3, 4)
.<Integer>mapMulti((n, sink) -> { sink.accept(n); if (n % 2 == 0) sink.accept(n); }).toList());
For ordinary code prefer flatMap, which reads better; reach for mapMulti when a profiler says the per-element streams matter. Operation order also matters for cost, not for the answer: put the cheapest, most selective filter first so later steps see fewer elements, and put limit before an expensive map when you only need the first few results.
Going deeper
- IntermediateOpsDemo.java — every operation above plus
mapMulti - Mastering Java Comparator — the comparators passed to
sorted - Mastering Java Optional — what
findFirstandminhand back
Terminal operations turn the pipeline into an answer, and some of them lie by omission
The terminal operation decides what you get back.reduce folds all elements into one value, the match family (anyMatch, allMatch, noneMatch) answers yes or no and short-circuits, findFirst returns the first element wrapped in an Optional, and count, min and max do what they say. From TerminalOpsDemo.java:
List<Integer> nums = List.of(1, 2, 3, 4, 5);
int sum = nums.stream().reduce(0, Integer::sum);
System.out.println("reduce(0, Integer::sum) : " + sum);
System.out.println("reduce((a,b) -> a*b) : " + nums.stream().reduce((a, b) -> a * b));
System.out.println("reduce on empty stream : " + Stream.<Integer>empty().reduce(Integer::sum));
System.out.println("reduce(\"\", join) : " + Stream.of("Java", "Streams", "are", "powerful")
.reduce("", (a, b) -> a.isEmpty() ? b : a + " " + b));
reduce(0, Integer::sum) : 15
reduce((a,b) -> a*b) : Optional[120]
reduce on empty stream : Optional.empty
reduce("", join) : Java Streams are powerful
Two details in that output are worth a pause. reduce with an identity value (0) always returns a plain value, but reduce without one returns an Optional, because an empty stream has nothing to fold: the output shows Optional.empty for the empty case. And the match methods have a rule that looks like a bug the first time:
List<Integer> data = List.of(3, 7, 1, 9, 4, 6);
System.out.println("anyMatch even : " + data.stream().anyMatch(n -> n % 2 == 0));
System.out.println("allMatch positive : " + data.stream().allMatch(n -> n > 0));
System.out.println("noneMatch negative : " + data.stream().noneMatch(n -> n < 0));
System.out.println("allMatch on empty stream : " + Stream.<Integer>empty().allMatch(n -> n > 100) + " <- vacuously true");
System.out.println("findFirst(n > 5) : " + data.stream().filter(n -> n > 5).findFirst());
System.out.println("count / min / max : " + data.stream().count() + " / "
+ data.stream().min(Integer::compare) + " / " + data.stream().max(Integer::compare));
anyMatch even : true
allMatch positive : true
noneMatch negative : true
allMatch on empty stream : true <- vacuously true
findFirst(n > 5) : Optional[7]
count / min / max : 6 / Optional[1] / Optional[9]
The most common terminal operation is collecting into a list, and there are two ways to do it that are not the same.allMatchon an empty stream istrue. It means “no element failed”, which is vacuously true when there are no elements. If you filter first and then callallMatchto mean “there is at least one and all are good”, you have a bug the moment the filter removes everything. Check the size or useanyMatchtoo.
Stream.toList() (Java 16) returns an unmodifiable list. Collectors.toList() returns an ordinary ArrayList you can change. Code that later calls add on the result works with one and throws with the other:
List<Integer> unmodifiable = Stream.of(1, 2, 3).toList();
List<Integer> mutable = Stream.of(1, 2, 3).collect(Collectors.toList());
mutable.add(4);
System.out.println("Collectors.toList() then add: " + mutable);
try {
unmodifiable.add(4);
} catch (UnsupportedOperationException e) {
System.out.println("Stream.toList() then add : UnsupportedOperationException");
}
System.out.println("toList() allows null elements: " + Stream.of("a", null).toList());
System.out.println("List.of(...) allows null : "
+ tryNull());
Collectors.toList() then add: [1, 2, 3, 4]
Stream.toList() then add : UnsupportedOperationException
toList() allows null elements: [a, null]
List.of(...) allows null : NullPointerException
Going deeper: which list do you actually want?
Default toStream.toList(): it is shorter, and an unmodifiable result cannot be changed by whoever receives it. Switch to Collectors.toList() only when the next line of code needs to mutate the list, and when you do, say why in a comment. Note also that Stream.toList() allows null elements (the output shows [a, null]) while List.of(...) throws a NullPointerException, so the two “immutable” lists are not interchangeable. Collectors.toUnmodifiableList() and List.copyOf are the stricter options that reject nulls.
forEach is a terminal operation too, and the one most often misused. If its body adds to an outside list, you have written a collector by hand and lost laziness, parallel safety and ordering guarantees; use collect or toList instead. The parallel section shows what that costs.
Going deeper
- TerminalOpsDemo.java — reduce, match, find, and the two kinds of list
- java.util.stream package summary — reduction, mutable reduction and side-effect rules
Collectors: grouping, counting and summing in one pass
Everything so far returned a list or a single value.collect takes a Collector, a ready-made recipe for the container you want, and the Collectors class has a recipe for most jobs. The one to learn first is groupingBy: it puts each element in a bucket chosen by a function, and an optional second argument, the downstream collector, summarises each bucket as it fills. All of these run against the same four orders (Order.java), and the code is in CollectorsCookbookDemo.java:
counting() and you get a count; pass summingDouble and you get a total. The code and the real output:
Map<String, List<Order>> byCountry = orders.stream().collect(groupingBy(Order::country));
System.out.println("byCountry : " + byCountry);
System.out.println("countByCustomer : " + orders.stream().collect(groupingBy(Order::customer, counting())));
System.out.println("revenueByCountry : " + orders.stream().collect(groupingBy(Order::country, summingDouble(Order::amount))));
System.out.println("productsByCountry : " + orders.stream()
.collect(groupingBy(Order::country, mapping(Order::product, toList()))));
byCountry : {IN=[Order[customer=ankur, product=laptop, amount=1200.0, country=IN], Order[customer=ankur, product=tablet, amount=400.0, country=IN]], US=[Order[customer=alex, product=phone, amount=800.0, country=US], Order[customer=brian, product=laptop, amount=1500.0, country=US]]}
countByCustomer : {ankur=2, alex=1, brian=1}
revenueByCountry : {IN=1600.0, US=2300.0}
productsByCountry : {IN=[laptop, tablet], US=[phone, laptop]}
partitioningBy is the special case where the bucket key is a yes/no test. It has one property that groupingBy lacks: it always returns both keys, so reading get(false) is safe even when nothing failed the test:
System.out.println("amount > 1000 : " + orders.stream().collect(partitioningBy(o -> o.amount() > 1000, counting())));
System.out.println("amount > 5000 : " + orders.stream().collect(partitioningBy(o -> o.amount() > 5000, counting()))
+ " <- both keys present even when one side is empty");
System.out.println("groupingBy > 5000 : " + orders.stream().collect(groupingBy(o -> o.amount() > 5000, counting()))
+ " <- only the keys that occurred");
== partitioningBy ==
amount > 1000 : {false=2, true=2}
amount > 5000 : {false=4, true=0} <- both keys present even when one side is empty
groupingBy > 5000 : {false=4} <- only the keys that occurred
toMapthrows on a duplicate key unless you give it a merge function. Ankur appears in two orders, sotoMap(Order::customer, Order::amount)cannot decide which amount to keep. It fails at run time, not compile time, and the message names the key and both values. GivetoMapa third argument that says how to combine them (Double::sumhere) any time the keys might repeat. Anullvalue also fails, with aNullPointerException, becausetoMapis built onHashMap.merge.
System.out.println("customerCsv : " + orders.stream().map(Order::customer).distinct().collect(joining(", ", "[", "]")));
System.out.println("toMap w/ merge : " + orders.stream()
.collect(toMap(Order::customer, Order::amount, Double::sum)));
try {
orders.stream().collect(toMap(Order::customer, Order::amount));
} catch (IllegalStateException e) {
System.out.println("toMap w/o merge : IllegalStateException: " + e.getMessage());
}
try {
orders.stream().collect(toMap(Order::customer, o -> (String) null, (a, b) -> a));
} catch (NullPointerException e) {
System.out.println("toMap null value : NullPointerException");
}
System.out.println("unmodifiable names : " + orders.stream().map(Order::customer).distinct()
.collect(collectingAndThen(toList(), List::copyOf)));
== joining, toMap, collectingAndThen ==
customerCsv : [ankur, alex, brian]
toMap w/ merge : {ankur=1600.0, alex=800.0, brian=1500.0}
toMap w/o merge : IllegalStateException: Duplicate key ankur (attempted merging values 1200.0 and 400.0)
toMap null value : NullPointerException
unmodifiable names : [ankur, alex, brian]
Going deeper: the full cookbook, one recipe per question
“I need a lookup map.”toMap(key, value, merge) as above; add a fourth argument such as TreeMap::new when you need sorted keys. “I need sorted group keys.” groupingBy(classifier, TreeMap::new, downstream); the demo prints {IN=2, US=2}. “I need the biggest item per group.” groupingBy(Order::country, maxBy(comparator)). The result is a Map<String, Optional<Order>> because maxBy is a general collector and its signature always returns an Optional; groups produced by groupingBy are never empty, so unwrapping with orElseThrow() is safe there.
Map<String, Optional<Order>> topByCountry = orders.stream()
.collect(groupingBy(Order::country, maxBy(Comparator.comparingDouble(Order::amount))));
System.out.println("topByCountry : " + topByCountry);
System.out.println("sorted keys (TreeMap): " + orders.stream()
.collect(groupingBy(Order::country, TreeMap::new, counting())));
topByCountry : {IN=Optional[Order[customer=ankur, product=laptop, amount=1200.0, country=IN]], US=Optional[Order[customer=brian, product=laptop, amount=1500.0, country=US]]}
sorted keys (TreeMap): {IN=2, US=2}
“I need an immutable result.” collectingAndThen(toList(), List::copyOf) applies a finishing step to any collector; the demo output is [ankur, alex, brian].
Going deeper: filtering, flatMapping and teeing (Java 9 and 12)
Filtering before groupingBy and filtering inside it are different: the first removes elements so a group can vanish, the second keeps the group and may leave it empty. With the test amount > 1300, only Brian’s 1500 order passes, so the filter-before form has no IN key at all, while filtering keeps IN=0. Use filtering when you need every group to be present in the report.
System.out.println("filtering (> 1300) : " + orders.stream()
.collect(groupingBy(Order::country, filtering(o -> o.amount() > 1300, counting()))));
System.out.println("filter then group : " + orders.stream()
.filter(o -> o.amount() > 1300).collect(groupingBy(Order::country, counting()))
+ " <- IN disappears: filter removes the element before grouping sees it");
System.out.println("flatMapping : " + orders.stream()
.collect(groupingBy(Order::country, flatMapping(o -> o.product().chars().mapToObj(c -> (char) c).limit(1), toList()))));
System.out.println("summarizingDouble : " + orders.stream().collect(summarizingDouble(Order::amount)));
== Java 9-12 additions ==
filtering (> 1300) : {IN=0, US=1}
filter then group : {US=1} <- IN disappears: filter removes the element before grouping sees it
flatMapping : {IN=[l, t], US=[p, l]}
summarizingDouble : DoubleSummaryStatistics{count=4, sum=3900.000000, min=400.000000, average=975.000000, max=1500.000000}
teeing (Java 12) runs two collectors over the same single pass and merges their results with a function, which is how you get a minimum, a maximum or an average without traversing twice. The demo’s average is 975.0, which matches the average=975.000000 in the summarizingDouble line above it; the min-and-max version builds a small record:
record MinMax(Order min, Order max) {}
System.out.println("teeing (min,max) : " + orders.stream().collect(teeing(
minBy(Comparator.comparingDouble(Order::amount)),
maxBy(Comparator.comparingDouble(Order::amount)),
(lo, hi) -> new MinMax(lo.orElseThrow(), hi.orElseThrow()))));
System.out.println("teeing (avg) : " + orders.stream().collect(teeing(
summingDouble(Order::amount), counting(), (total, n) -> total / n)));
teeing (min,max) : MinMax[min=Order[customer=ankur, product=tablet, amount=400.0, country=IN], max=Order[customer=brian, product=laptop, amount=1500.0, country=US]]
teeing (avg) : 975.0
Going deeper
- CollectorsCookbookDemo.java — every recipe on this page, runnable
- output/05-collectorscookbook.txt — the full captured output
- Collectors (JDK 25 Javadoc) — the complete list of factory methods
- Java HashMap vs ConcurrentHashMap — what a collected
Mapactually is - Understanding LinkedHashMap in Java — when you need insertion order in the result
Primitive streams avoid boxing, and int sums overflow without a sound
A Stream<Integer> holds Integer objects, so every number is boxed and unboxed on its way through. IntStream, LongStream and DoubleStream hold raw primitives, skip that cost, and add numeric helpers the object stream lacks: sum(), average() and summaryStatistics(). Use mapToInt (or mapToDouble) to switch from an object stream and boxed() to switch back. From PrimitiveStreamsDemo.java:
System.out.println("rangeClosed(1,100).sum() : " + IntStream.rangeClosed(1, 100).sum());
IntSummaryStatistics st = IntStream.of(3, 1, 4, 1, 5, 9, 2, 6).summaryStatistics();
System.out.println("summaryStatistics : " + st);
List<String> words = List.of("hello", "world", "streams");
System.out.println("mapToInt(length).sum() : " + words.stream().mapToInt(String::length).sum());
System.out.println("average of empty IntStream : " + IntStream.empty().average());
System.out.println("sum of empty IntStream : " + IntStream.empty().sum());
System.out.println("boxed().toList() : " + IntStream.of(3, 1, 2).sorted().boxed().toList());
rangeClosed(1,100).sum() : 5050
summaryStatistics : IntSummaryStatistics{count=8, sum=31, min=1, average=3.875000, max=9}
mapToInt(length).sum() : 17
average of empty IntStream : OptionalDouble.empty
sum of empty IntStream : 0
boxed().toList() : [1, 2, 3]
Notice that the average of an empty IntStream is OptionalDouble.empty and not 0: an average of nothing is undefined, so the type forces you to handle it. The sum of nothing really is 0.
IntStream.sum()overflows silently. AddingInteger.MAX_VALUEand 1 gives-2147483648, with no exception. Widening to alongfirst (asLongStream()ormapToLong) gives the right2147483648, andMath.addExactturns the overflow into anArithmeticExceptionif you would rather fail loudly. The boxedStream<Integer>withInteger::sumwraps in exactly the same way.
// Overflow: IntStream.sum() wraps silently. LongStream does not, until you pass Long.MAX_VALUE.
System.out.println("IntStream sum overflow : " + IntStream.of(Integer.MAX_VALUE, 1).sum());
System.out.println("asLongStream sum : " + IntStream.of(Integer.MAX_VALUE, 1).asLongStream().sum());
try {
IntStream.of(Integer.MAX_VALUE, 1).mapToLong(i -> i).reduce(0L, Math::addExact);
System.out.println("Math.addExact in long : no overflow");
} catch (ArithmeticException e) {
System.out.println("Math.addExact : " + e.getMessage());
}
try {
IntStream.of(Integer.MAX_VALUE, 1).reduce(0, Math::addExact);
} catch (ArithmeticException e) {
System.out.println("Math.addExact in int : " + e.getMessage());
}
System.out.println("Stream<Integer>.reduce sum : " + Stream.of(Integer.MAX_VALUE, 1).reduce(0, Integer::sum) + " <- also wraps");
IntStream sum overflow : -2147483648
asLongStream sum : 2147483648
Math.addExact in long : no overflow
Math.addExact in int : integer overflow
Stream<Integer>.reduce sum : -2147483648 <- also wraps
Going deeper: when boxing actually matters
Boxing is a cost per element, so it matters on large numeric pipelines and is noise on a list of ten items. The honest rule: if the data is numeric and the pipeline is justmap then sum, use the primitive stream because it is also the clearer code; do not rewrite a readable Stream<Integer> pipeline on a hunch. If you do care about the number, measure it with JMH rather than guessing; the parallel streams benchmark post shows a case where boxing changed the winner.
Going deeper
- PrimitiveStreamsDemo.java — statistics, the empty-stream cases and the overflow demo
- IntStream (JDK 25 Javadoc)
Parallel streams: one method call, and sometimes a wrong answer
Adding.parallel() splits the source, runs the pieces on a shared pool of threads, and merges the results. It is safe only when your operations are stateless and associative: it must not matter how the pieces are grouped. Summing numbers is. The demo in ParallelDemo.java shows a safe case, an ordering case, and two ways to get a wrong answer without any exception:
System.out.println("parallel sum 1..1_000_000 : "
+ LongStream.rangeClosed(1, 1_000_000L).parallel().sum() + " <- associative, stateless: safe");
StringBuilder a = new StringBuilder();
IntStream.rangeClosed(1, 10).parallel().forEachOrdered(n -> a.append(n).append(' '));
System.out.println("forEachOrdered : " + a.toString().trim());
List<Integer> viaToList = IntStream.rangeClosed(1, 10).parallel().boxed().toList();
System.out.println("parallel ... toList() : " + viaToList + " <- order IS preserved by collectors");
int seq = IntStream.rangeClosed(1, 10).boxed().reduce(0, (x, y) -> x - y);
int par = IntStream.rangeClosed(1, 10).boxed().parallel().reduce(0, (x, y) -> x - y);
int total = 200_000;
List<Integer> unsafe = new ArrayList<>();
try {
IntStream.range(0, total).parallel().forEach(unsafe::add);
System.out.println("ArrayList.add from forEach : size " + unsafe.size() + " (expected " + total
+ ") <- lost or duplicated writes are possible");
} catch (RuntimeException e) {
System.out.println("ArrayList.add from forEach : " + e.getClass().getSimpleName() + " (list corrupted mid-run)");
}
List<Integer> safe = IntStream.range(0, total).parallel().boxed().toList();
System.out.println("collect/toList instead : size " + safe.size());
parallel sum 1..1_000_000 : 500000500000 <- associative, stateless: safe
== forEach vs forEachOrdered (encounter order) ==
forEachOrdered : 1 2 3 4 5 6 7 8 9 10
parallel ... toList() : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <- order IS preserved by collectors
sequential 0-1-2-...-10 : -55
parallel (same lambda) : 15 <- subtraction is not associative
== shared mutable state ==
ArrayList.add from forEach : size 196740 (expected 200000) <- lost or duplicated writes are possible
collect/toList instead : size 200000
Common pool parallelism : 1
Two numbers above are machine-dependent, and I want you to treat them that way. The parallel result of the subtractionreduceand the final size of the unsafely filledArrayListboth depend on how the source was split and how threads were scheduled, and this sandbox had one common-pool worker (the last line of the capture says so). On your machine the numbers will differ; the point is that the sequential answer is-55, the parallel answer is something else, and the list is smaller than the 200000 you expected. A run could also throw from insideArrayList; the demo catches that case too. Neither result is a bug in the JDK: the lambda broke the rules.
Encounter order is kept by collectors, not byforEach. The paralleltoList()in the output returned[1, 2, ..., 10]in order, andforEachOrderedprinted in order. PlainforEachon a parallel stream has no such guarantee, and that is why the old advice “never build a list insideforEach” is really “letcollectdo the merging”.
Going deeper: speed, the common pool, and when to still say yes
Correctness is only half of it. A parallel stream usually loses on small inputs, on cheap per-element work, on linked sources, and on pipelines that block, because every parallel stream in the JVM shares oneForkJoinPool.commonPool(). All of that is measured with JMH, with error columns, in Java Parallel Streams: When They’re Slower; this section does not repeat it. The short version: benchmark first, parallelise only large CPU-bound pipelines over arrays, ArrayList or ranges, and for blocking work use virtual threads (Virtual Threads vs Platform Threads).
Going deeper
- ParallelDemo.java — the three scenarios above, runnable
- Java Parallel Streams: When They’re Slower — the measured side of this topic
- Java Concurrency Deep Dive — the pool underneath
- Multithreading Example in Java
Stream Gatherers add the intermediate operations Stream never had
Stream has a fixed list of intermediate operations, and for years the only way to add your own was to drop down to a hand-written Spliterator. A gatherer is a pluggable intermediate operation, applied with .gather(...), and the JDK ships five in the Gatherers class. They became final in JDK 24 (JEP 485); older write-ups that call them a preview feature in JDK 22 are out of date. Here are all five on the numbers 1 to 7, from GatherersDemo.java:
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7);
System.out.println("windowFixed(3) : " + nums.stream().gather(Gatherers.windowFixed(3)).toList());
System.out.println("windowSliding(3) : " + nums.stream().gather(Gatherers.windowSliding(3)).toList());
System.out.println("scan (running sum) : " + nums.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
System.out.println("fold (one result) : " + nums.stream().gather(Gatherers.fold(() -> 0, Integer::sum)).toList());
System.out.println("mapConcurrent(2) : " + nums.stream().gather(Gatherers.mapConcurrent(2, n -> n * 10)).toList());
windowFixed(3) : [[1, 2, 3], [4, 5, 6], [7]]
windowSliding(3) : [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
scan (running sum) : [1, 3, 6, 10, 15, 21, 28]
fold (one result) : [28]
mapConcurrent(2) : [10, 20, 30, 40, 50, 60, 70]
scan emits every running total, fold emits only the final one as a one-element stream, and mapConcurrent(2, f) runs f on up to two virtual threads at once while keeping the results in the original order. A moving average, which used to need a custom Spliterator, is a sliding window plus a map:
List<Double> moving = nums.stream().gather(Gatherers.windowSliding(3))
.map(w -> w.stream().mapToInt(Integer::intValue).average().orElse(0)).toList();
System.out.println("3-point moving avg : " + moving);
3-point moving avg : [2.0, 3.0, 4.0, 5.0, 6.0]
Going deeper: writing your own gatherer
A gatherer has an optional state object, an integrator that receives each element plus a handle to push results downstream, and optional combiner and finisher steps. The smallest useful one is sequential: it keeps one value of state and pushes an element only when it differs from the previous one. That is “drop adjacent duplicates”, whichdistinct() cannot express because distinct() removes all duplicates, not just neighbouring ones:
Supplier<int[]> lastSeen = () -> new int[] {Integer.MIN_VALUE};
Gatherer<Integer, int[], Integer> dedupeAdjacent = Gatherer.ofSequential(
lastSeen,
(state, element, downstream) -> {
if (element != state[0]) {
state[0] = element;
return downstream.push(element);
}
return true;
});
System.out.println("dedupeAdjacent : " + Stream.of(1, 1, 2, 2, 2, 1, 3, 3).gather(dedupeAdjacent).toList()
+ " <- distinct() would give [1, 2, 3]");
dedupeAdjacent : [1, 2, 1, 3] <- distinct() would give [1, 2, 3]
The integrator returns true to say “keep sending me elements” and false to short-circuit, and push itself returns false once downstream does not want more. That return value is why a gatherer composes with limit without any extra code. The javap listing in output/00-javap-gatherers.txt is the primary-source confirmation of the five built-in gatherers on this JDK.
Going deeper
- GatherersDemo.java — the five gatherers and the custom one
- output/00-javap-gatherers.txt —
javap java.util.stream.Gatherers - JEP 485: Stream Gatherers — delivered in JDK 24, preceded by JEP 461 (JDK 22) and JEP 473 (JDK 23)
- Gatherer (JDK 25 Javadoc)
Turning a for loop into a pipeline without changing what it does
Most people meet streams while rewriting a loop, and four things can change on the way. From LoopToStreamDemo.java, the plain case first: filter, then sum per country. The loop and the pipeline give the same map:Map<String, Double> loopRevenue = new TreeMap<>();
for (Order o : orders) {
if (o.amount() >= 500) {
loopRevenue.merge(o.country(), o.amount(), Double::sum);
}
}
Map<String, Double> streamRevenue = orders.stream()
.filter(o -> o.amount() >= 500)
.collect(groupingBy(Order::country, TreeMap::new, summingDouble(Order::amount)));
== 1. The straightforward conversion ==
loop : {IN=1200.0, US=2300.0}
stream : {IN=1200.0, US=2300.0}
equal : true
A loop with a break becomes findFirst, not filter: filter would keep testing every element after the first match.
Order firstBig = null;
for (Order o : orders) {
if (o.amount() > 1000) {
firstBig = o;
break;
}
}
Optional<Order> viaStream = orders.stream().filter(o -> o.amount() > 1000).findFirst();
== 2. A loop with break becomes findFirst, not filter ==
loop : ankur/laptop
stream : ankur/laptop
A list a loop built with new ArrayList<>() was mutable, but the list from toList() is not, so any later add now throws (section 3 of output/09-looptostream.txt shows both lists). And a lambda cannot update a plain local counter (it can only use variables that never change), so beginners reach for an int[] trick that works but is a side effect; the real fix is to ask the pipeline for the answer with count():
int[] hits = {0};
orders.stream().filter(o -> o.country().equals("US")).forEach(o -> hits[0]++);
System.out.println("works, but it is a side effect: " + hits[0]);
long clean = orders.stream().filter(o -> o.country().equals("US")).count();
== 4. A loop can update a counter; a lambda cannot ==
works, but it is a side effect: 2
the pipeline way (count) : 2
(a plain `int hits` would not compile: lambdas capture effectively-final variables only)
Going deeper: five prompts for doing this refactor with an AI assistant
The refactors below are mechanical enough that an assistant does them well, as long as you ask it to explain the behaviour differences listed above. Paste a prompt into Claude, ChatGPT or Cursor together with the code. These are prompts, not Java, so they are not in the repository.1. Refactor a for-loop. Refactor this imperative Java for-loop into a Stream pipeline. Use method references where possible, prefer Stream.toList() over collect(toList()), and explain any behaviour differences (e.g. short-circuiting, null handling, encounter-order changes). Use it whenever a loop filters, transforms or aggregates a collection.
2. Collapse nested loops. Convert this nested loop that builds a Map<Group, List<Item>> into a single Collectors.groupingBy pipeline. Preserve insertion ordering if the original used a LinkedHashMap. A very common shape in legacy code.
3. Choose the right collector. Given this aggregation requirement: [describe what you want], recommend the right Collector combination from: groupingBy, partitioningBy, summingDouble, mapping, collectingAndThen. Show the complete code with imports. For when you know the result you want but not the collector.
4. Performance review. Review this Stream pipeline for performance issues: unnecessary boxing (use mapToInt/mapToDouble), repeated traversal, parallelStream misuse on small/IO-bound collections, and collector inefficiency. Suggest concrete fixes with before/after snippets. Use it when profiling points at a data-processing hot path, or before enabling parallelStream.
5. Modernise toList(). Find every collect(Collectors.toList()) in this file. Replace with Stream.toList() where the result is not mutated downstream. Flag any call sites where mutation would cause a runtime UnsupportedOperationException after the change. Part of a Java 16+ modernisation pass.
Going deeper
- LoopToStreamDemo.java — the four conversions above
- Java 21 to Java 25 Upgrade Guide (with AI Prompts) — more prompts for modernisation passes
- Java 21 to Java 25 LTS: Every Feature You Actually Need to Know
The mistakes that cost people an afternoon
Each row is a behaviour shown earlier on this page or pinned by a contract test, with the symptom you will actually see.| Pitfall | What you see | Fix |
|---|---|---|
| Reusing a stream | IllegalStateException: stream has already been operated upon or closed | Keep the source, create a new stream each time |
Side effects in peek or map | They run, or silently do not, depending on the rest of the pipeline (count() skipped peek above) | Use peek only for debugging; do real work in the terminal operation |
| Mutating shared state in a lambda | Wrong results, a short list or an exception under .parallel() | Stateless lambdas; collect into a new object instead |
Using forEach to build a collection | Defeats laziness, breaks parallelism, order not guaranteed | Use collect() or toList() |
toMap with duplicate keys | IllegalStateException: Duplicate key ankur (attempted merging values 1200.0 and 400.0) | Pass a merge function as the third argument |
toList() result then modified | UnsupportedOperationException | Collectors.toList() only if you must mutate |
takeWhile used as filter | Elements after the first failure vanish | Use filter unless the data is ordered |
allMatch on an empty stream | Returns true | Check emptiness separately |
IntStream.sum() near the int limit | Wraps to a negative number, no exception | Widen to long or use Math.addExact |
Non-associative reduce in parallel | A different answer from the sequential run | Use associative operations, or stay sequential |
| Parallel streams on small data | Pool overhead makes it slower than sequential | Benchmark first; see the linked JMH post |
Quick reference: every operation at a glance
| Operation | Type | Returns | Notes |
|---|---|---|---|
filter(Predicate) | Intermediate | Stream<T> | Keeps elements matching the predicate |
map(Function) | Intermediate | Stream<R> | 1-to-1 transform |
flatMap(Function) | Intermediate | Stream<R> | 1-to-many transform, then flatten |
mapMulti(BiConsumer) | Intermediate | Stream<R> | Java 16; push 0..n outputs without a stream per element |
distinct() | Intermediate | Stream<T> | Uses equals(); stateful |
sorted() | Intermediate | Stream<T> | Natural or custom Comparator; stateful barrier |
limit(n) | Intermediate | Stream<T> | First n elements; short-circuits |
skip(n) | Intermediate | Stream<T> | Drop first n elements |
takeWhile / dropWhile | Intermediate | Stream<T> | Java 9; act on the leading run only |
peek(Consumer) | Intermediate | Stream<T> | Debug observer; may not run (see count()) |
gather(Gatherer) | Intermediate | Stream<R> | JDK 24; windows, scan, fold, mapConcurrent, custom |
collect(Collector) | Terminal | R | Most versatile terminal op |
toList() | Terminal | List<T> | Java 16+; unmodifiable, allows null |
reduce(identity, BinaryOp) | Terminal | T | Fold to a single value; Optional<T> without identity |
forEach(Consumer) | Terminal | void | Side effects; order not guaranteed in parallel |
count() | Terminal | long | May skip the pipeline when the size is known |
min / max(Comparator) | Terminal | Optional<T> | |
anyMatch / allMatch / noneMatch | Terminal | boolean | Short-circuit; allMatch is true when empty |
findFirst / findAny | Terminal | Optional<T> | findAny may be faster in parallel |
Frequently asked questions
Is Stream.toList() the same as Collectors.toList()?
No. Stream.toList() (Java 16+) returns an unmodifiable list: any attempt to add, remove or replace elements throws UnsupportedOperationException, as the output in the terminal-operations section shows. Collectors.toList() returns a mutable ArrayList. Use Stream.toList() by default and switch only when you need to mutate the result.
When should I use parallelStream()?
Only for CPU-heavy transformations over large in-memory collections where the per-element cost is significant, and only after you have benchmarked it. The common ForkJoinPool overhead frequently outweighs the gain on small or I/O-bound streams. The measured thresholds are in the parallel streams benchmark post.
Can I reuse a stream?
No. Once a terminal operation has run the stream is consumed and throwsIllegalStateException if used again. Create a new stream from the source each time. If you need several terminal operations over the same data, collect it with toList() once and stream from the list as often as you like.
Why does toMap() throw IllegalStateException?
The two-argument form toMap(keyMapper, valueMapper) throws when two elements produce the same key; the message names the key and both values. Supply a third argument, a merge function such as Double::sum, whenever duplicate keys are possible.
Does peek always run?
No. Since the JDK may skip the pipeline for count() when the size is known from the source, a peek in front of it can print nothing, as the laziness section shows. Treat peek as a debugging aid only.
Should you use a stream here at all?
An honest rule of thumb. Use a stream when the loop is a pure “filter, transform, summarise” over a collection: the pipeline is shorter and states its intent. Keep the loop when the body needsbreakorcontinueon several conditions, updates several variables, throws checked exceptions, or is easier to step through in a debugger. A long chain of lambdas that nobody can name is worse than the loop it replaced. Streams are a tool for expressing computations, not a goal in themselves, and none of this changes the Java Collections you started from: see the Collections guide for choosing the source type.
Conclusion
The Streams API is built on three ideas. Laziness: nothing runs until a terminal operation, and then each element travels the whole pipeline alone. Composability: intermediate operations chain without intermediate collections, andCollectors compose too, so groupingBy plus a downstream collector replaces whole loops of manual map handling. Optional parallelism: .parallel() is one call, but it is correct only for stateless, associative work. Fluency with filter, map, flatMap and the collector recipes covers most real code; the edge cases on this page (toMap duplicates, count() skipping peek, int overflow, takeWhile versus filter) are what separate knowing the API from understanding it. Run scripts/run-all.sh in the companion module to regenerate every output block on this page.
Further reading
- java-core-examples / streams — every file referenced in this post, the captured output and the contract tests.
- Java Functional Interfaces: Function, Predicate, Supplier and Consumer Explained
- Java Collections Framework: Choosing the Right Data Structure
- Parameterized Tests in JUnit 6: All Sources Explained with Examples
- Multithreading Example in Java
- Java 21 to Java 25 LTS: Every Feature You Actually Need to Know
- Java Concurrency Deep Dive: CompletableFuture, ExecutorService, ForkJoinPool
- Virtual Threads vs Platform Threads — Benchmarks and Code
- Mastering Java Comparator: A Practical Guide to Custom Sorting
- Understanding LinkedHashMap in Java
- Java LinkedHashSet: Order-Preserving Uniqueness
- Mastering TreeSet in Java
- Java HashMap vs ConcurrentHashMap: Complete Guide
- Apache Commons Collection — MultiValuedMap
- Java 21 to Java 25 Upgrade Guide (with AI Prompts)
- Mastering Java Optional: Eliminate NullPointerExceptions for Good
- Java Generics: The Complete Developer’s Reference
- Java Parallel Streams: When They’re Slower (JMH Benchmarks and the Common Pool)
- JDK Javadoc — java.util.stream.Collectors
- JDK Javadoc — java.util.stream package overview
- JEP 485 — Stream Gatherers (final in JDK 24)
- Brian Goetz — State of the Lambda: Libraries Edition (design rationale)
No Comments yet!