Stream pitfalls, readability and performance
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A good stream pipeline is correct first, easy to read second and fast enough third. Most stream bugs in real projects come from a short list of repeated mistakes, and most "streams are slow" worries disappear once you compare honestly with a loop.
Streams versus loops: speed and readability
For simple work on small or medium lists, a plain for loop is often a little faster than a stream. The stream builds a pipeline object and calls a lambda per element; the loop does neither. With boxed Integer elements the gap grows, with IntStream it shrinks. In real programs the difference is usually microseconds, far smaller than one database call or one network request.
So speed rarely decides. Readability does: how fast a teammate can read the code and be sure it is right. "Filter the passed students, take their marks, average them" reads better as three stream steps than as a loop with a counter, a total and an if.
A loop wins when the logic needs index juggling, an early break with several changing variables, a running value such as a wallet balance after each payment, or checked exceptions that must reach the caller. Pick the version a reader understands fastest; measure only when a real speed problem appears.
Pipeline length, naming and when to split
Write one step per line, so each line says one thing. When a lambda grows beyond one short line, move it into a method with a clear name: filter(this::isEligibleForScholarship) explains itself, while a four-line lambda with && and || does not.
Example 1 · Split a long pipeline into named pieces
import java.util.List;import java.util.function.Predicate;
record Student(String name, String branch, int marks, int attendance, boolean feesPaid) { }
public class ReadablePipelineDemo { static final Predicate<Student> PASSED = s -> s.marks() >= 40; static final Predicate<Student> REGULAR = s -> s.attendance() >= 75;
static boolean eligibleForScholarship(Student s) { return PASSED.and(REGULAR).test(s) && s.feesPaid() && s.marks() >= 85; }
public static void main(String[] args) { List<Student> all = List.of( new Student("Aarav", "CSE", 91, 88, true), new Student("Priya", "ECE", 87, 70, true), new Student("Rohan", "CSE", 95, 92, false), new Student("Kavya", "CSE", 86, 80, true), new Student("Imran", "ME", 38, 90, true));
// hard to read: every rule squeezed into one lambda List<String> before = all.stream() .filter(s -> s.marks() >= 40 && s.attendance() >= 75 && s.feesPaid() && s.marks() >= 85) .map(s -> s.name() + " (" + s.branch() + ")") .toList();
// easier to read: the rule has a name List<String> after = all.stream() .filter(ReadablePipelineDemo::eligibleForScholarship) .map(s -> s.name() + " (" + s.branch() + ")") .toList();
System.out.println("Before: " + before); System.out.println("After: " + after); System.out.println("Passed but irregular: " + all.stream().filter(PASSED.and(REGULAR.negate())).map(Student::name).toList()); }}Before: [Aarav (CSE), Kavya (CSE)] After: [Aarav (CSE), Kavya (CSE)] Passed but irregular: [Priya]
What this code does
- Both pipelines give the same list, but the second one reads as a sentence: keep the students eligible for a scholarship, show name and branch. The rule can be tested on its own.
- Named predicates such as
PASSEDandREGULARare reused and combined withandandnegate, so the same rule is never written twice in slightly different ways.
Named Predicate variables help too: Predicate<Student> passed = s -> s.marks() >= 40;. They can be reused and combined with and, or and negate. Split a pipeline when it does two jobs, such as cleaning data and building a report, or when it passes about six steps. Store the middle result in a well-named List, never in a Stream variable, because a stream can be used only once.
Checked exceptions inside lambdas
The functional interfaces used by streams, such as Function and Predicate, declare no checked exceptions. So a method that throws IOException cannot be used directly in map: the compiler says "unreported exception IOException; must be caught or declared to be thrown".
Example 2 · A checked exception inside map
import java.io.IOException;import java.util.List;
public class CheckedErrorDemo { // stands in for reading a student's marks file static int loadMarks(String roll) throws IOException { if (roll.startsWith("X")) { throw new IOException("no file for " + roll); } return roll.length() * 20; }
public static void main(String[] args) throws IOException { List<String> rolls = List.of("101", "1022", "10"); List<Integer> marks = rolls.stream().map(r -> loadMarks(r)).toList(); System.out.println(marks); }}CheckedErrorDemo.java:15: error: unreported exception IOException; must be caught or declared to be thrown
List<Integer> marks = rolls.stream().map(r -> loadMarks(r)).toList();
^
1 errorWhat this code does
maptakes aFunction, andFunction.applydeclares no checked exceptions, so the lambda body may not throwIOException.throws IOExceptiononmaindoes not help: the exception would leave the lambda, which is a separate method, notmainitself.
Example 3 · Two fixes: wrap or skip
import java.io.IOException;import java.io.UncheckedIOException;import java.util.List;import java.util.stream.Stream;
public class CheckedFixDemo { static int loadMarks(String roll) throws IOException { if (roll.startsWith("X")) { throw new IOException("no file for " + roll); } return roll.length() * 20; }
// fix 1: wrap - one failure stops the whole job static int loadOrFail(String roll) { try { return loadMarks(roll); } catch (IOException e) { throw new UncheckedIOException(e); } }
// fix 2: skip - a bad roll gives an empty stream and a message static Stream<Integer> loadOrSkip(String roll) { try { return Stream.of(loadMarks(roll)); } catch (IOException e) { System.out.println("Skipped: " + e.getMessage()); return Stream.empty(); } }
public static void main(String[] args) { List<String> rolls = List.of("101", "X77", "1022");
List<Integer> kept = rolls.stream().flatMap(CheckedFixDemo::loadOrSkip).toList(); System.out.println("Loaded: " + kept);
try { rolls.stream().map(CheckedFixDemo::loadOrFail).toList(); } catch (UncheckedIOException e) { System.out.println("Job stopped: " + e.getCause().getMessage()); } }}Skipped: no file for X77 Loaded: [60, 80] Job stopped: no file for X77
What this code does
loadOrFailturns the checkedIOExceptioninto an uncheckedUncheckedIOException, so it fits inmap. The caller can still catch it and read the original withgetCause().loadOrSkipreturns a stream of one value or an empty stream, andflatMapjoins them, so bad rolls simply drop out. The message is the one side effect, for a log.
Adding throws to main does not help, because the lambda is a different method.
There are three usual fixes:
- Wrap: a small helper method catches the checked exception and throws an unchecked one, such as
UncheckedIOExceptionor your ownRuntimeException. Use this when one failure should stop the whole job. - Skip or default: the helper catches the exception and returns a default, or an empty stream through
flatMap, and maybe records the bad item. Use this when bad rows should be reported but not stop the rest. - Loop: when the caller must handle the checked exception itself, a plain loop is the honest choice.
A checklist of common stream mistakes
These are the mistakes this section has warned about, in one place. Check a pipeline against them before you call it done.
- Using a stream twice: "stream has already been operated upon or closed".
Example 4 · Five classic mistakes and what they throw
import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;
public class MistakesDemo { public static void main(String[] args) { // 1. using a stream twice Stream<String> cities = Stream.of("Pune", "Goa", "Pune"); System.out.println("Count: " + cities.count()); try { cities.count(); } catch (IllegalStateException e) { System.out.println("1. " + e.getMessage()); }
// 2. no terminal operation: the lambda never runs Stream.of("a", "b").map(s -> { System.out.println("never printed"); return s; }); System.out.println("2. nothing ran without a terminal operation");
// 3. toMap with a duplicate key try { Stream.of("Pune", "Goa", "Pune").collect(Collectors.toMap(c -> c, c -> 1)); } catch (IllegalStateException e) { System.out.println("3. " + e.getMessage()); }
List<Integer> marks = new ArrayList<>(List.of(70, 35, 90)); try { marks.stream().forEach(m -> { if (m < 40) { marks.add(40); } }); } catch (RuntimeException e) { System.out.println("4. " + e.getClass().getSimpleName()); }
try { List.of(55, 62).stream().filter(m -> m > 90).findFirst().get(); } catch (RuntimeException e) { System.out.println("5. " + e.getClass().getSimpleName() + ": " + e.getMessage()); } }}Count: 3 1. stream has already been operated upon or closed 2. nothing ran without a terminal operation 3. Duplicate key Pune (attempted merging values 1 and 1) 4. ConcurrentModificationException 5. NoSuchElementException: No value present
What this code does
- Each mistake fails in its own way: a reused stream and duplicate
toMapkeys throwIllegalStateException; a missing terminal operation fails silently, which is the hardest to spot. - Changing the source list throws
ConcurrentModificationException, andget()on an emptyOptionalthrowsNoSuchElementException. The fixes are a fresh stream, a terminal operation, a merge function, a separate result list andorElse.
Build a fresh stream each time.
- No terminal operation: nothing runs, not even the
peekormaplambdas. - Side effects: adding to an outside list or counter instead of
toList,countorgroupingBy. - Changing the source list inside the pipeline:
ConcurrentModificationException. get()orgetAsInt()on an empty Optional:NoSuchElementException; useorElse.toMapwith duplicate keys:IllegalStateException; add a merge function.- An infinite
iterateorgeneratewith nolimitortakeWhile, orsortedon it. IntStream.sum()overflow, andparallel()on small data, blocking calls, shared state or a non-associativereduce.
Next step
Check your understanding
12 quick questions