Sub topic 15
Common Stream Mistakes and How to Avoid Them
Streams are short and easy to read, but some mistakes come up again and again. Several of them compile fine and then fail at run time. Others never fail and quietly give wrong answers later. This chapter covers the most common ones, shows what goes wrong, and gives a safe fix for each.
Two terms come up throughout:
- A side effect is any change a lambda makes outside itself, such as adding to an outside list, changing a field, or printing.
- A stateful lambda is a lambda whose result depends on something it remembers between calls, such as a set of items it has already seen.
Mistake 1: Reusing a Stream
A stream is a one-time pass over the data. After a terminal operation runs, the stream is consumed, which means it is used up. Calling another operation on it throws an IllegalStateException.
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");
}
}
}A collection is different. You can loop over a List as many times as you like. A stream is closer to a water tap: once the water has run out, you need to turn the tap on again.
The fix: make a new stream each time
The simplest fix is to call .stream() again on the collection. If you want to reuse the same pipeline steps, wrap them in a Supplier. A Supplier<T> is a functional interface whose get() method returns a new value each time you call it.
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class SupplierExample {
public static void main(String[] args) {
List<String> words = List.of("sun", "moon", "star");
Supplier<Stream<String>> longWords =
() -> words.stream().filter(w -> w.length() > 3);
System.out.println(longWords.get().count()); // 2
System.out.println(longWords.get().anyMatch(w -> w.equals("moon"))); // true
}
}Each call to get() builds a fresh stream, so neither call ever touches a stream that has already been consumed.
Mistake 2: Forgetting the Terminal Operation
Streams are lazy. Intermediate operations such as filter and map only describe the work. Nothing runs until a terminal operation asks for elements.
import java.util.List;
public class NoTerminalExample {
public static void main(String[] args) {
List<String> names = List.of("ann", "ben");
names.stream().map(n -> {
System.out.println("Processing " + n);
return n.toUpperCase();
}); // no terminal operation, so this prints nothing
System.out.println("Done");
}
}This program prints only Done. The compiler does not warn you. If a pipeline seems to do nothing, check that it ends with an operation such as collect, count, forEach, or findFirst.
Mistake 3: Changing Outside State from a Lambda
Beginners often build a result by adding to a list from inside forEach:
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, 5, 6);
// Risky: the lambda changes a list that lives 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, 6]
// 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, 6]
}
}Both versions print the same thing here. The first one is still fragile. If someone later adds .parallel(), several threads may call add on the same ArrayList at once. ArrayList is not safe for that. Elements can go missing, or the program can throw an exception. The collect version stays correct in both cases, because the collector manages its own containers.
Counting with an outside variable
Another common attempt looks like this:
int count = 0;names.stream().forEach(n -> count++);
This does not compile. Java reports: local variables referenced from a lambda expression must be final or effectively final. "Effectively final" means the variable is never changed after it is first assigned. Some people work around the rule with an int[] array or an AtomicInteger. Don't. Ask the stream for the answer instead:
import java.util.List;
public class CountExample {
public static void main(String[] args) {
List<String> names = List.of("ann", "ben", "cara");
long count = names.stream()
.filter(n -> n.length() == 3)
.count();
System.out.println(count); // 2
}
}Mistake 4: Modifying the Source While Streaming
Never add elements to the source collection, or remove them from it, while a stream over that collection is running.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class ModifySourceExample {
public static void main(String[] args) {
List<String> items = new ArrayList<>(List.of("a", "b", "c"));
try {
items.stream().forEach(s -> items.add(s + s));
} catch (ConcurrentModificationException e) {
System.out.println("Do not change the source while streaming");
}
}
}ArrayList notices that it changed during the pass and throws a ConcurrentModificationException. Other collections may not throw at all and simply give unpredictable results. The fix is to collect the new elements into a separate list, then add them afterward:
List<String> extra = items.stream().map(s -> s + s).collect(Collectors.toList());items.addAll(extra);
Mistake 5: Stateful Lambdas
This filter removes duplicates by remembering what it has seen:
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class StatefulExample {
public static void main(String[] args) {
List<String> words = List.of("red", "blue", "red", "green", "blue");
// Stateful: depends on a set that changes on every call
Set<String> seen = new HashSet<>();
List<String> risky = words.stream()
.filter(seen::add)
.collect(Collectors.toList());
System.out.println(risky); // [red, blue, green]
// Stateless lambda, built-in deduplication
List<String> safe = words.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(safe); // [red, blue, green]
}
}seen.add returns true only the first time it sees a word, so the trick works on one thread. In a parallel stream it can break, and a reader has to think hard to see why it works at all. distinct() says what you mean and handles the details for you. As a rule, a lambda's result should depend only on its input.
How the Mistakes Fit Together
Summary Table
| Mistake | What happens | Fix |
|---|---|---|
| Reusing a stream | `IllegalStateException` | Call `.stream()` again or use a `Supplier` |
| No terminal operation | Nothing runs, silently | End with `collect`, `count`, `forEach`, and so on |
| Adding to an outside list | Breaks in parallel | Use `collect` |
| Changing a local counter | Compile error | Use `count`, `sum`, or `reduce` |
| Modifying the source | `ConcurrentModificationException` or odd results | Collect first, change afterward |
| Stateful lambda | Wrong results in parallel | Use `distinct`, `sorted`, or `limit` |
Exercise
This code throws an exception on its second line. Why, and how do you fix it? Stream<String> s = List.of("a", "b").stream(); long n = s.count(); boolean has = s.anyMatch(x -> x.equals("a"));
Show answer
count() is a terminal operation, so it consumes the stream. Calling anyMatch on the same stream then throws IllegalStateException. Fix it by creating a new stream for each question, for example List.of("a", "b").stream().anyMatch(...), or by keeping the list in a variable and calling .stream() on it twice.
Exercise
Rewrite this so that no lambda changes outside state: List<String> out = new ArrayList<>(); names.stream().map(String::trim).forEach(out::add);
Show answer
List<String> out = names.stream().map(String::trim).collect(Collectors.toList()); The collector builds the list itself, so the code stays correct even if the stream becomes parallel.
Exercise
A teammate writes numbers.stream().filter(n -> n > 0).map(n -> n * 2); and says it "does nothing". What is wrong?
Show answer
The pipeline has no terminal operation. Streams are lazy, so filter and map never run. Add a terminal operation such as .collect(Collectors.toList()) and use the result.