Advanced streams
A stream pipeline is a description of work that runs only when a terminal operation pulls elements through it, one at a time. Knowing that explains most of what streams do, including the surprises. This page traces elements through a pipeline, runs the operations added from Java 9 to 16, builds advanced and custom collectors, looks at the spliterator flags that let streams skip work, runs five common traps, and measures streams against a plain loop.
Contents
How a stream pipeline runs
A stream (Java 8) has three parts: a source such as a collection or a range, any number of intermediate operations such as filtermaptoListcountfindFirstSpliterator
Two properties follow from this design. Operations can short-circuit: findFirstanyMatchlimitsorteddistinct
| Feature | Since | What it does | Best for |
|---|---|---|---|
takeWhiledropWhile | Java 9 | Keep or skip elements until a test first fails | Sorted or time-ordered data |
Stream.iterate(seed, hasNext, next)ofNullable | Java 9 | A finite iterate; a stream of zero or one element | Loop-like sequences, optional values |
Collectors.filteringflatMapping | Java 9 | Filter or flatten inside a downstream collector | Per-group processing in groupingBy |
Collectors.teeing | Java 12 | Two collectors over one pass, results merged | Two aggregates at once |
mapMultiStream.toList() | Java 16 | Emit any number of results per element; collect to an unmodifiable list | Flattening without inner streams; the usual end of a pipeline |
Gatherers (Stream.gather | Java 24 | Custom intermediate operations | Windows, scans, stateful steps; see |
Basic operations such as groupingBy
Watching elements flow through a pipeline
Each stage prints when it handles an element, so the order of the printed lines shows how the stream really runs. The word list includes short and long words so that filter
import java.util.List;
import java.util.stream.Stream;
public class Laziness {
public static void main(String[] args) {
List<String> words = List.of("apple", "banana", "cherry", "date", "elderberry", "fig");
// Building the pipeline runs nothing
Stream<String> pipeline = words.stream()
.filter(w -> {
System.out.println(" filter " + w);
return w.length() > 4;
})
.map(w -> {
System.out.println(" map " + w);
return w.toUpperCase();
});
System.out.println("pipeline built, nothing printed yet");
// The terminal operation pulls elements one at a time, through all stages
System.out.println("findFirst -> " + pipeline.findFirst().orElse("-"));
// limit short-circuits: only as many elements as needed are processed
System.out.println("limit(2):");
List<String> two = words.stream()
.peek(w -> System.out.println(" saw " + w))
.filter(w -> w.contains("e"))
.limit(2)
.toList();
System.out.println(" result " + two);
// sorted is a barrier: it must see every element before passing any on
System.out.println("sorted then findFirst:");
String first = words.stream()
.peek(w -> System.out.println(" saw " + w))
.sorted()
.findFirst()
.orElse("-");
System.out.println(" result " + first);
}
}
Output:
pipeline built, nothing printed yet
filter apple
map apple
findFirst -> APPLE
limit(2):
saw apple
saw banana
saw cherry
result [apple, cherry]
sorted then findFirst:
saw apple
saw banana
saw cherry
saw date
saw elderberry
saw fig
result apple
- Building the pipeline printed nothing. Only
started it, and it stopped after the first element: "apple" passed the filter, was mapped, and was the answer. The other five words were never read.findFirst - Filter and map alternate per element ("filter apple", "map apple") rather than filtering everything first. This is vertical processing, one element at a time through all stages.
- With
, the stream read apple (kept), banana (no "e"), cherry (kept), and stopped: three elements read to produce two results. "date", "elderberry" and "fig" were never touched.limit(2) beforesorted() had to read all six words, because the smallest one could be anywhere. Placing short-circuiting and filtering operations before barriers saves work; on an infinite stream, a barrier before the short-circuit never finishes.findFirst
Operations added in Java 9 to 16
A list of sensor readings that rises and then drops shows the difference between takeWhilefiltermapMulti
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class NewerOperations {
record Order(String id, List<String> items) { }
public static void main(String[] args) {
List<Integer> readings = List.of(3, 5, 8, 13, 2, 21, 1);
// takeWhile / dropWhile (Java 9): stop or start at the first element that fails
System.out.println("takeWhile < 10: " + readings.stream().takeWhile(n -> n < 10).toList());
System.out.println("dropWhile < 10: " + readings.stream().dropWhile(n -> n < 10).toList());
System.out.println("filter < 10: " + readings.stream().filter(n -> n < 10).toList());
// iterate with a condition (Java 9): like a for loop
System.out.println("iterate powers of 2 below 100: "
+ Stream.iterate(1, n -> n < 100, n -> n * 2).toList());
// ofNullable (Java 9): zero or one element
Map<String, String> config = Map.of("host", "db1");
System.out.println("ofNullable count for host/port: "
+ Stream.ofNullable(config.get("host")).count() + "/"
+ Stream.ofNullable(config.get("port")).count());
// mapMulti (Java 16): emit any number of results per element, without a stream per element
List<Order> orders = List.of(new Order("o1", List.of("pen", "ink")),
new Order("o2", List.of()), new Order("o3", List.of("pad")));
List<String> lines = orders.stream()
.<String>mapMulti((o, out) -> {
for (String item : o.items()) {
out.accept(o.id() + ":" + item);
}
})
.toList();
System.out.println("mapMulti: " + lines);
// toList() (Java 16) is unmodifiable; Collectors.toList() makes no such promise
List<Integer> unmodifiable = IntStream.range(0, 3).boxed().toList();
List<Integer> mutable = IntStream.range(0, 3).boxed().collect(Collectors.toList());
mutable.add(3);
System.out.println("Collectors.toList() after add: " + mutable);
try {
unmodifiable.add(3);
} catch (UnsupportedOperationException e) {
System.out.println("Stream.toList().add: UnsupportedOperationException");
}
}
}
Output:
takeWhile < 10: [3, 5, 8]
dropWhile < 10: [13, 2, 21, 1]
filter < 10: [3, 5, 8, 2, 1]
iterate powers of 2 below 100: [1, 2, 4, 8, 16, 32, 64]
ofNullable count for host/port: 1/0
mapMulti: [o1:pen, o1:ink, o3:pad]
Collectors.toList() after add: [0, 1, 2, 3]
Stream.toList().add: UnsupportedOperationException
stopped at 13, the first failure, and never looked at the 2 and 1 after it;takeWhile(n -> n < 10) kept them.filter is the complement, starting at 13 and keeping everything after it. On an unordered source, such as adropWhile , which elements count as "first" is undefined.HashSet- The three-argument
works like aStream.iterate loop: seed 1, continue while below 100, double each time.for gave one element for the existing key and none for the missing one, which is handy insideStream.ofNullable .flatMap pushed one line per item into the consumer and nothing for the empty order. It does the job ofmapMulti without creating a small stream per element, which is cheaper when most elements produce zero or one result.flatMap returns an unmodifiable list, soStream.toList() threwadd .UnsupportedOperationException returned anCollectors.toList() here, but its Javadoc promises nothing about mutability. UseArrayList when you need a list you can change.Collectors.toCollection(ArrayList::new)
Advanced collectors: teeing, filtering, flatMapping
Five transactions over three accounts are enough to show each collector, and account A has no transaction over 200, which is exactly the case where filteringfilter
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class TeeingAndMore {
record Txn(String account, String type, double amount, Set<String> tags) {
}
public static void main(String[] args) {
List<Txn> txns = List.of(
new Txn("A", "debit", 120.0, Set.of("food")),
new Txn("B", "credit", 900.0, Set.of("salary")),
new Txn("A", "debit", 45.5, Set.of("food", "travel")),
new Txn("C", "debit", 300.0, Set.of("rent")),
new Txn("B", "debit", 60.0, Set.of("travel")));
// teeing (Java 12): two collectors over one pass, then merge their results
record MinMax(double min, double max) {
}
MinMax range = txns.stream().collect(Collectors.teeing(
Collectors.minBy((a, b) -> Double.compare(a.amount(), b.amount())),
Collectors.maxBy((a, b) -> Double.compare(a.amount(), b.amount())),
(lo, hi) -> new MinMax(lo.orElseThrow().amount(), hi.orElseThrow().amount())));
System.out.println("teeing min/max: " + range);
double share = txns.stream().collect(Collectors.teeing(
Collectors.filtering(t -> t.type().equals("debit"),
Collectors.summingDouble(Txn::amount)),
Collectors.summingDouble(Txn::amount),
(debits, all) -> debits / all * 100));
System.out.printf("debits are %.1f%% of all volume%n", share);
// filtering (Java 9): keeps groups that end up empty, unlike filter() before grouping
Map<String, Long> bigByAccount = txns.stream().collect(Collectors.groupingBy(
Txn::account, TreeMap::new,
Collectors.filtering(t -> t.amount() > 200, Collectors.counting())));
System.out.println("txns over 200 per account (filtering): " + bigByAccount);
Map<String, Long> withFilterFirst = txns.stream().filter(t -> t.amount() > 200)
.collect(Collectors.groupingBy(Txn::account, TreeMap::new, Collectors.counting()));
System.out.println("same with filter() first: " + withFilterFirst);
// flatMapping (Java 9): flatten a collection per element inside a group
Map<String, Set<String>> tagsByAccount = txns.stream().collect(Collectors.groupingBy(
Txn::account, TreeMap::new,
Collectors.flatMapping(t -> t.tags().stream(),
Collectors.toCollection(TreeSet::new))));
System.out.println("tags per account: " + tagsByAccount);
// summarizing: count, sum, min, average, max at once
DoubleSummaryStatistics stats = txns.stream()
.collect(Collectors.summarizingDouble(Txn::amount));
System.out.printf("stats: n=%d sum=%.1f avg=%.2f%n", stats.getCount(), stats.getSum(),
stats.getAverage());
}
}
Output:
teeing min/max: MinMax[min=45.5, max=900.0]
debits are 36.9% of all volume
txns over 200 per account (filtering): {A=0, B=1, C=1}
same with filter() first: {B=1, C=1}
tags per account: {A=[food, travel], B=[salary, travel], C=[rent]}
stats: n=5 sum=1425.5 avg=285.10
sent every element to two collectors,teeing andminBy , and merged their results into a record, in one pass over the data. The second use divided the debit sum (525.5) by the total (1,425.5): 36.9%.maxBy insideCollectors.filtering kept account A with a count of 0. Filtering before grouping removed A completely, because no element of A reached the collector. When reports must show every group, filter downstream.groupingBy flattened each transaction's tag set into one sorted set per account.flatMapping computed count, sum, minimum, average and maximum together, here 5 transactions with an average of 285.10.summarizingDouble
Writing a custom Collector
A collector is four functions: a supplier that creates a mutable container, an accumulator that adds one element, a combiner that merges two containers from parallel parts, and an optional finisher that turns the container into the result. The first collector wraps words into lines of at most 20 characters; the second computes a maximum with 0 for an empty stream.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.IntStream;
public class CustomCollector {
// Collects strings into lines no longer than 'width', like word wrapping
static Collector<String, List<StringBuilder>, List<String>> wrap(int width) {
return Collector.of(
ArrayList::new, // supplier: new container
(lines, word) -> { // accumulator: add one element
if (lines.isEmpty()
|| lines.get(lines.size() - 1).length() + 1 + word.length() > width) {
lines.add(new StringBuilder(word));
} else {
lines.get(lines.size() - 1).append(' ').append(word);
}
},
(left, right) -> { // combiner: merge two partials
left.addAll(right);
return left;
},
lines -> lines.stream().map(StringBuilder::toString).toList()); // finisher
}
// A simpler custom collector: running max with Collector.of and an int[] holder
static Collector<Integer, int[], Integer> maxOrZero() {
return Collector.of(
() -> new int[] {0},
(box, n) -> box[0] = Math.max(box[0], n),
(a, b) -> {
a[0] = Math.max(a[0], b[0]);
return a;
},
box -> box[0]);
}
public static void main(String[] args) {
String text = "the quick brown fox jumps over the lazy dog and keeps on running";
List<String> wrapped = List.of(text.split(" ")).stream().collect(wrap(20));
wrapped.forEach(line -> System.out.println("|" + line + "|"));
int max = IntStream.rangeClosed(1, 100).boxed().parallel().collect(maxOrZero());
System.out.println("max of 1..100 (parallel): " + max);
int empty = List.<Integer>of().stream().collect(maxOrZero());
System.out.println("max of empty stream: " + empty);
}
}
Output:
|the quick brown fox|
|jumps over the lazy|
|dog and keeps on|
|running|
max of 1..100 (parallel): 100
max of empty stream: 0
- The words were packed into lines of up to 20 characters. The container is a list of
s, and the finisher converts them to strings, so callers never see the mutable state.StringBuilder - The maximum collector ran on a parallel stream and gave 100. Each worker accumulated into its own
holder, and the combiner merged the holders. An empty stream returned 0 from the supplier's initial value.int[] - The combiner of the wrapping collector only concatenates line lists, so in a parallel stream two half-full lines could meet at a chunk boundary without being joined. A combiner must give the same result as sequential accumulation; this one is correct only for sequential streams, which is worth stating in its documentation.
also takes characteristics such asCollector.of andUNORDERED that let the stream skip work.IDENTITY_FINISH
Spliterator characteristics: how streams skip work
Every stream starts from a Spliterator
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.TreeSet;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Characteristics {
static String flags(Spliterator<?> s) {
Map<String, Integer> all = new LinkedHashMap<>();
all.put("ORDERED", Spliterator.ORDERED);
all.put("DISTINCT", Spliterator.DISTINCT);
all.put("SORTED", Spliterator.SORTED);
all.put("SIZED", Spliterator.SIZED);
all.put("SUBSIZED", Spliterator.SUBSIZED);
all.put("NONNULL", Spliterator.NONNULL);
all.put("IMMUTABLE", Spliterator.IMMUTABLE);
List<String> on = new ArrayList<>();
all.forEach((name, bit) -> {
if (s.hasCharacteristics(bit)) {
on.add(name);
}
});
return on + ", estimateSize " + s.estimateSize();
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(5, 3, 8));
Set<Integer> hash = new HashSet<>(list);
Set<Integer> tree = new TreeSet<>(list);
System.out.println("ArrayList: " + flags(list.spliterator()));
System.out.println("List.of: " + flags(List.of(5, 3, 8).spliterator()));
System.out.println("HashSet: " + flags(hash.spliterator()));
System.out.println("TreeSet: " + flags(tree.spliterator()));
System.out.println("IntStream.range: " + flags(IntStream.range(0, 1000).spliterator()));
System.out.println("after filter: "
+ flags(list.stream().filter(n -> n > 4).spliterator()));
System.out.println("Stream.iterate: "
+ flags(Stream.iterate(1, n -> n + 1).spliterator()));
// SIZED lets count() skip the pipeline entirely (Java 9 and later)
int[] peeked = new int[1];
long count = list.stream().peek(n -> peeked[0]++).count();
System.out.println("count() = " + count + ", peek ran " + peeked[0] + " times");
long filteredCount = list.stream().peek(n -> peeked[0]++).filter(n -> n > 4).count();
System.out.println("with filter: count() = " + filteredCount + ", peek total now "
+ peeked[0]);
}
}
Output:
ArrayList: [ORDERED, SIZED, SUBSIZED], estimateSize 3
List.of: [ORDERED, SIZED, SUBSIZED], estimateSize 3
HashSet: [DISTINCT, SIZED], estimateSize 3
TreeSet: [ORDERED, DISTINCT, SORTED, SIZED], estimateSize 3
IntStream.range: [ORDERED, DISTINCT, SORTED, SIZED, SUBSIZED, NONNULL, IMMUTABLE], estimateSize 1000
after filter: [ORDERED], estimateSize 3
Stream.iterate: [ORDERED, IMMUTABLE], estimateSize 9223372036854775807
count() = 3, peek ran 0 times
with filter: count() = 2, peek total now 3
- A list is
andORDERED ; aSIZED isHashSet but not ordered; aDISTINCT is alsoTreeSet , soSORTED on it with natural order does nothing andsorted() on any set is free.distinct() has every flag, includingIntStream.range , which means it splits into exactly known halves, ideal for parallel work.SUBSIZED - After
, the stream is no longerfilter : the estimate of 3 is just an upper bound. An infiniteSIZED reportsiterate as its size.Long.MAX_VALUE - Because the list is
,SIZED returned 3 without running the pipeline:count() ran 0 times. Since Java 9, thepeek Javadoc allows this. With acount in the way the size is unknown, so the pipeline ran andfilter saw all 3 elements. Never put logic that must run inpeek .peek
Five stream traps
The mistakes below compile without warnings. The race in the second case does not fail every time, so the program repeats it 10 times and reports whether any attempt went wrong.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamTraps {
public static void main(String[] args) {
// 1. A stream can be consumed only once
Stream<String> s = Stream.of("a", "b");
s.count();
try {
s.count();
} catch (IllegalStateException e) {
System.out.println("1. reuse: IllegalStateException: " + e.getMessage());
}
// 2. Adding to a shared ArrayList from a parallel stream is a data race
int brokenRuns = 0;
for (int attempt = 0; attempt < 10; attempt++) {
List<Integer> unsafe = new ArrayList<>();
try {
IntStream.range(0, 100000).parallel().forEach(unsafe::add);
if (unsafe.size() != 100000) {
brokenRuns++; // elements lost
}
} catch (ArrayIndexOutOfBoundsException e) {
brokenRuns++; // internal array corrupted
}
}
boolean broken = brokenRuns > 0;
List<Integer> safe = IntStream.range(0, 100000).parallel().boxed().toList();
System.out.println("2. forEach(list::add) broke in some of 10 runs: " + broken
+ "; toList() size " + safe.size());
// 3. Parallel forEach ignores encounter order; forEachOrdered keeps it
List<Integer> order = Collections.synchronizedList(new ArrayList<>());
IntStream.range(0, 1000).parallel().forEachOrdered(order::add);
List<Integer> expected = IntStream.range(0, 1000).boxed().toList();
System.out.println("3. forEachOrdered kept order: " + order.equals(expected));
// 4. Collectors.toMap throws on duplicate keys unless given a merge function
List<String> names = List.of("ann", "bob", "amy");
try {
names.stream().collect(Collectors.toMap(n -> n.charAt(0), n -> n));
} catch (IllegalStateException e) {
System.out.println("4. toMap: " + e.getMessage());
}
System.out.println("4. with merge: " + names.stream().collect(
Collectors.toMap(n -> n.charAt(0), n -> n, (x, y) -> x + "+" + y)));
// 5. Infinite streams need a short-circuit before any barrier
List<Integer> firstSquares = Stream.iterate(1, n -> n + 1).map(n -> n * n).limit(5)
.toList();
System.out.println("5. limit before collecting an infinite stream: " + firstSquares
+ " (sorted() before limit would never finish)");
}
}
Output:
1. reuse: IllegalStateException: stream has already been operated upon or closed
2. forEach(list::add) broke in some of 10 runs: true; toList() size 100000
3. forEachOrdered kept order: true
4. toMap: Duplicate key a (attempted merging values ann and amy)
4. with merge: {a=ann+amy, b=bob}
5. limit before collecting an infinite stream: [1, 4, 9, 16, 25] (sorted() before limit would never finish)
- A stream is single-use. The second
threwcount() . Keep the source, or aIllegalStateException , if you need to run the pipeline again.Supplier<Stream<T>> - Adding to a shared
from a parallelArrayList lost elements or threwforEach in some of the 10 runs. Collecting withArrayIndexOutOfBoundsException gave all 100,000, because each worker fills its own container and the results are combined. Side effects on shared state are the most common parallel stream bug.toList() - A parallel
processes elements in whatever order the workers reach them.forEach kept the encounter order, at the cost of waiting for earlier chunks.forEachOrdered threwCollectors.toMap for the duplicate key 'a', naming both values. With a merge function as the third argument, the values were combined.IllegalStateException- An infinite stream works only if a short-circuiting operation such as
comes before any barrier.limit would run until memory ran out.Stream.iterate(1, n -> n + 1).sorted()
Streams versus loops: speed
The same calculation, the sum of the squares of the even values among 20 million numbers, runs as a forIntStreamStream<Integer>IntStream
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class StreamVsLoop {
interface Job {
long run();
}
static long best(Job job) {
long best = Long.MAX_VALUE;
for (int i = 0; i < 5; i++) {
long t0 = System.nanoTime();
job.run();
best = Math.min(best, System.nanoTime() - t0);
}
return best / 1000000;
}
public static void main(String[] args) {
int n = 20000000;
List<Integer> boxed = new ArrayList<>(n);
int[] prims = new int[n];
for (int i = 0; i < n; i++) {
boxed.add(i % 1000);
prims[i] = i % 1000;
}
// sum of squares of the even values
long loop = best(() -> {
long sum = 0;
for (int v : prims) {
if (v % 2 == 0) {
sum += (long) v * v;
}
}
return sum;
});
long intStream = best(() -> IntStream.of(prims).filter(v -> v % 2 == 0)
.mapToLong(v -> (long) v * v).sum());
long boxedStream = best(() -> boxed.stream().filter(v -> v % 2 == 0)
.map(v -> (long) v * v).reduce(0L, Long::sum));
long parallel = best(() -> IntStream.of(prims).parallel().filter(v -> v % 2 == 0)
.mapToLong(v -> (long) v * v).sum());
System.out.printf("20,000,000 values, best of 5 runs:%n");
System.out.printf("for loop over int[] %,4d ms%n", loop);
System.out.printf("IntStream over int[] %,4d ms%n", intStream);
System.out.printf("Stream<Integer> + reduce %,4d ms%n", boxedStream);
System.out.printf("parallel IntStream %,4d ms%n", parallel);
}
}
Output (2-CPU Linux machine with JDK 21, best of 5):
20,000,000 values, best of 5 runs:
for loop over int[] 43 ms
IntStream over int[] 38 ms
Stream<Integer> + reduce 104 ms
parallel IntStream 19 ms
- The
was as fast as the loop. Once the JIT inlines the lambdas, the pipeline compiles down to much the same machine code.IntStream - The boxed
withStream<Integer> was two to three times slower: it readsreduce objects scattered on the heap and creates aInteger for every partial sum. UseLong ,mapToInt andmapToLong for numbers.sum() - The parallel stream took about half the time of the loop on 2 cores, because an
splits evenly and the work per element is uniform. For small inputs, or sources likeint[] that split badly, parallel is often slower; seeLinkedListFork/Join .
Choosing stream tools
| Need | Use |
|---|---|
| A list result | toList()Collectors.toCollection(ArrayList::new) |
| Stop at the first element that fails a test | takeWhile |
| Zero or more outputs per element | flatMapmapMulti |
| Two aggregates in one pass | Collectors.teeing |
| Filter but keep empty groups | groupingByCollectors.filtering |
| A reusable, unusual aggregation | Collector.of |
| A custom intermediate step | |
| Numeric work | IntStreamLongStreamDoubleStream |
| Side effects or complex control flow | A plain loop |
See findFirstmax