Lesson · Stream API
Stream traps: the six failures everyone meets
13 min readTraps & Best Practices
Streams fail in a small number of distinctive ways: single-use, laziness, unbounded sources, duplicate keys, source mutation and Optional.get. Recognizing the exception is most of the diagnosis.
Trap 1: a stream is single-use
A stream is a one-shot source of elements. The first terminal operation consumes it; a second operation on the same object throws immediately, with a message that names the mistake: stream has already been operated upon or closed.
The fix is structural, not defensive: don't store streams in fields or pass them between methods that each expect to consume them. Pass the list, and let each consumer build its own pipeline.
Stream<String> s = Stream.of("a", "b"); s.forEach(System.out::print); // ab s.count(); // IllegalStateException: stream has already been operated upon or closed
Trap 2: laziness means nothing ran
Intermediate operations build a plan and execute none of it. A pipeline with no terminal operation is a described computation that never happens: no exception, no output, no effect. When a pipeline seems ignored, look for the missing terminal first.
The same laziness can bite in the other direction with unbounded sources: sorted or distinct over an infinite stream wait forever for the stream to end, so the pipeline never emits. Bounding operations must come before the stateful one.
One measured surprise: count() in Java 9+ can answer from the source size alone when no operation changed it, skipping the entire pipeline including peek. If the elements must actually be processed, end with forEach or a collector instead of count.
Stream.of("a", "b").peek(System.out::println); // prints nothing, ever Stream.iterate(1, n -> n + 1).sorted().limit(3); // never completes Stream.iterate(1, n -> n + 1).limit(3).sorted(); // [1, 2, 3]
Trap 3: toMap duplicates
Collectors.toMap refuses to lose data silently: when two elements produce the same key it throws IllegalStateException with a message naming the key and both values: Duplicate key go (attempted merging values 2 and 2).
That exception is a signal that the code never stated a collision policy. Add the merge function: Integer::max keeps the best, (a, b) -> a keeps the first, (a, b) -> a + b adds them.
Trap 4: mutating the source during traversal
A stream is a view over its source. Adding to or removing from the backing collection while the pipeline iterates it trips the fail-fast check and throws ConcurrentModificationException. The pipeline did not 'race'; the source changed shape under an active traversal.
Filter into a new collection, or collect first and mutate after. Changing definitions of the data is a different operation from reading it.
List<String> list = new ArrayList<>(List.of("a", "b", "c")); list.stream().peek(x -> list.add("x")).forEach(x -> { }); // ConcurrentModificationException
Trap 5: Optional.get on empty
Optional models 'a value may be absent', and get() (or getAsInt on primitive Optionals) throws NoSuchElementException when it is. The existence of get is a fact about the API, not a permission for the call site to ignore absence.
The chosen terminal tells you the danger: findFirst, min, max and one-argument reduce on an empty stream all return an empty Optional, and the decision about the empty case is yours to make: orElse, orElseThrow, ifPresent, or a filter upstream that guarantees non-emptiness.
Trap 6: side effects in the pipeline
peek exists for observing, and using it to mutate shared state couples the pipeline to execution details you do not control: how many times each element is processed, in what order, and on which thread, all of which change under parallel().
The correction is not 'be careful with peek', it is 'accumulate with collect or reduce'. A pipeline that mutates external state behind the scenes behaves correctly in the editor and incorrectly in production, which is the worst combination of properties.
Two of these traps throw loudly (reuse, toMap duplicates). The other four are silent: nothing ran, mutated source, missing value, hidden side effect. Silent traps are why the rules exist, not why they are remembered.
Trap gallery · wrong line, exact symptom, correction
8 traps, 4 throw · 4 stay silentIllegalStateException: Duplicate key go (attempted merging values 2 and 2)
wrong
collect(toMap(w -> w, String::length)) // two 'go' keys
fix
state the policy: toMap(w -> w, String::length, Integer::max)
Read the exception, name the trap
IllegalStateException mentioning operated upon or closed is trap 1. IllegalStateException mentioning Duplicate key is trap 3. ConcurrentModificationException is trap 4. NoSuchElementException from findFirst or min is trap 5. Each message points directly at the broken assumption.
Interview angles
Why can't you use a stream twice?+
A stream is single-use by contract: it carries mutable traversal state. The first terminal consumes that state and a second attempt sees it spent and throws IllegalStateException. Pass the source and build a fresh pipeline per consumer.
A pipeline with no visible effect, what do you check?+
Whether it has a terminal operation. Intermediate operations are lazy: without a terminal, the entire pipeline is a plan that never executes, silently.
Why does Stream.iterate(...).sorted().limit(3) hang?+
sorted is stateful: it must see every element before emitting the first. An infinite source never finishes feeding it, so limit never receives an element. Put limit before sorted and the stream becomes finite first.
What does 'Duplicate key' from toMap tell you?+
Two elements produced the same key and no merge function was provided, so the collector refused to silently drop one. Supply a merge function (max, first, last, concatenate) to state the policy.
Is forEach with a shared collection ever acceptable in a parallel stream?+
No. Writes from multiple threads race with lost updates and possible crashes. Collectors exist for exactly this: per-chunk containers, merged at the end, no shared state.