Sub topic 15
Common Stream Mistakes and How to Avoid Them
Streams are easy to read, but a few mistakes come up often. This chapter covers three of them: reusing a stream, changing outside data from inside a lambda, and writing lambdas that remember earlier elements.
Mistake 1: Reusing a Stream
A stream can be used only once. Once a terminal operation (the last step, such as count or collect) runs, the stream is consumed. Consumed means it is finished and cannot run again. If you call another operation on it, Java throws an IllegalStateException, which is an error that means "this object is in the wrong state for that call."
import java.util.List;
import java.util.stream.Stream;
public class ReuseExample {
public static void main(String[] args) {
Stream<String> stream = List.of("x", "y").stream();
System.out.println(stream.count()); // 2
try {
stream.count();
} catch (IllegalStateException e) {
System.out.println("A stream can be consumed only once");
}
}
}The fix is to make a new stream each time. The list stays the same, so you can call .stream() on it as often as you need.
Mistake 2: Side Effects in Lambdas
A side effect is a change a piece of code makes to something outside itself. One example is adding items to a list that was declared before the stream. This works in simple cases, but it hides your intent, and it breaks with parallel streams. Let the stream build the result for you instead.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SideEffectExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4);
// Risky: the lambda changes a list outside the stream
List<Integer> evensBad = new ArrayList<>();
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(n -> evensBad.add(n));
System.out.println(evensBad); // [2, 4]
// Better: let the stream build the list
List<Integer> evensGood = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evensGood); // [2, 4]
}
}Mistake 3: Stateful Lambdas
A stateful lambda remembers things between elements. For example, it might keep a running count or a "seen before" set. The result can then depend on the order in which elements arrive, and that order is not guaranteed in parallel streams.
Java helps here. A lambda cannot change a local variable from the code around it. That variable must be effectively final, which means it is never reassigned after it is first set. So count++ inside a lambda will not compile. Use the built-in operations instead:
| Instead of a stateful lambda that... | Use |
|---|---|
| counts elements | `count()` |
| skips repeated elements | `distinct()` |
| adds up values | `sum()` or `reduce` |
Quick Checklist
- Make a fresh stream for each pipeline.
- Use
collectortoListto build results. Do not useforEachto fill an outside list. - Keep lambdas simple: input goes in, output comes out, and nothing else changes.
Exercise
This code fails at runtime. Why, and how do you fix it? Stream<String> s = List.of("a", "b").stream(); long n = s.count(); List<String> all = s.collect(Collectors.toList());
Show answer
The call to count() consumes the stream, so collect throws an IllegalStateException. Fix it by creating a new stream for the second pipeline: List<String> all = List.of("a", "b").stream().collect(Collectors.toList()); The cleaner version keeps the list in a variable and calls list.stream() twice.
Exercise
Why is collect(Collectors.toList()) a better choice than forEach(list::add) for building a result list?
Show answer
collect builds the list inside the stream without changing outside state. That makes the intent clear, and it stays correct if the stream runs in parallel. forEach(list::add) changes a shared list as a side effect.