A stream can be used only once
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A stream is a one-time flow: once its values have passed through to a terminal operation, the stream is used up and cannot run again. The source collection, on the other hand, stays exactly as it was, and it must not be changed while the stream is reading it.
Why a stream works only once
Consumed stream is a stream whose terminal operation has already run. It is closed and cannot be used again; any further operation on it throws an IllegalStateException.
A stream keeps no copy of its values. It reads them from the source as they flow, hands each one on, and forgets it. After the terminal operation, there is nothing left to replay, so the stream is marked consumed: used up and closed.
Example 1 · Using a stream twice
import java.util.List;import java.util.stream.Stream;
public class UsedTwiceDemo { public static void main(String[] args) { List<String> register = List.of("Aarav", "Diya", "Kabir"); Stream<String> names = register.stream();
System.out.println("Count: " + names.count()); try { names.forEach(n -> System.out.println(n)); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } }}Count: 3 Error: stream has already been operated upon or closed
What this code does
count()is a terminal operation, so it consumesnames. The second terminal operation,forEach, finds the stream already used and throws.- The
try/catchonly shows the message here. In real code, the fix is a new stream, not catching the error.
The same is true one step earlier. When you call an intermediate operation such as filter on a stream object, that object is now linked to the new stage. Calling a second operation on the same old object is also not allowed. A list is like a printed class register: you can read it as often as you like. A stream is like the roll call itself: once every name has been called, the roll call is over, and you start a new one if you need it again.
The error message
Using a stream a second time throws IllegalStateException with the message "stream has already been operated upon or closed". An exception is an error object Java throws while the program runs; IllegalStateException means the object is in the wrong state for that call.
Example 2 · The real crash and its stack trace
import java.util.List;import java.util.stream.Stream;
public class ReuseCrashDemo { public static void main(String[] args) { List<String> marks = List.of("P", "A", "P"); Stream<String> present = marks.stream().filter(m -> m.equals("P"));
System.out.println("Present: " + present.count()); System.out.println("As a list: " + present.toList()); }}Present: 2 Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:246) at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:616) at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:622) at java.base/java.util.stream.ReferencePipeline.toList(ReferencePipeline.java:627) at ReuseCrashDemo.main(ReuseCrashDemo.java:10)
What this code does
- The first line prints fine. The second use of
presentstops the program withIllegalStateException, and the last line of the trace points at line 10, wheretoList()is called. - Nothing warned at compile time. This is why the bug often reaches testing or users: the code looks correct.
The compiler cannot catch this mistake, because the code is correct Java. It shows up only at run time, often in a part of the program that was not tested. When you see the message, look for a variable of type Stream that is used twice.
Trap: keeping a stream in a variable
It feels natural to build a filtered stream once and use it for several answers: a count, a list, a check. With a list that works; with a stream the second use fails.
Example 3 · Trap: two steps on the same stream object
import java.util.List;import java.util.stream.Stream;
public class TwoBranchesDemo { public static void main(String[] args) { Stream<Integer> fees = List.of(1200, 0, 4500).stream(); Stream<Integer> due = fees.filter(f -> f > 0);
try { Stream<Integer> withFine = fees.map(f -> f + 100); System.out.println(withFine.toList()); } catch (IllegalStateException e) { System.out.println("map on fees: " + e.getMessage()); }
System.out.println("Fees due: " + due.toList()); }}map on fees: stream has already been operated upon or closed Fees due: [1200, 4500]
What this code does
fees.filter(...)linkedfeesto a new stage, sofees.map(...)fails at once, before any terminal operation runs. A stream cannot split into two branches.- The pipeline that was linked,
due, still works. Build two separate pipelines from the list when you need two different results.
There are three clean fixes. Call list.stream() again for each answer; this is cheap, because creating a stream copies nothing. If several answers start with the same steps, keep those steps in a Supplier<Stream<T>>. And if you need the filtered data many times, collect it once with toList() and reuse that list.
Find the bug
Find the second use
Tap the line that is wrong, then check the fix.
Count the passes, then list them.
Round 1 of 2Supplier<Stream<T>>: a fresh stream on demand
A Supplier<T> is the functional interface from java.util.function whose method get() takes nothing and returns a value. If the lambda inside it builds a stream, every call to get() builds a new one.
Example 4 · The fixes: a new stream or a Supplier
import java.util.List;import java.util.function.Supplier;import java.util.stream.Stream;
record Entry(String name, boolean present) {}
public class FreshStreamDemo { public static void main(String[] args) { List<Entry> register = List.of( new Entry("Aarav", true), new Entry("Diya", false), new Entry("Kabir", true), new Entry("Meera", true), new Entry("Rohan", false));
// fix 1: call stream() again for each answer long absent = register.stream().filter(e -> !e.present()).count(); System.out.println("Absent count: " + absent);
// fix 2: keep the shared steps in a Supplier Supplier<Stream<Entry>> present = () -> register.stream().filter(Entry::present); System.out.println("Present count: " + present.get().count()); System.out.println("Present names: " + present.get().map(Entry::name).toList()); System.out.println("Meera present? " + present.get().anyMatch(e -> e.name().equals("Meera"))); }}Absent count: 2 Present count: 3 Present names: [Aarav, Kabir, Meera] Meera present? true
What this code does
- Every
present.get()runs the lambda again and returns a brand new stream, so the three uses never clash. - The Supplier stores the recipe, register then filter, in one place. If the rule for "present" changes, it changes once.
So Supplier<Stream<Entry>> present = () -> register.stream().filter(Entry::present); stores the recipe, not the stream. present.get().count() and present.get().toList() each start a fresh pipeline from the source. A method that returns list.stream().filter(...) works the same way, because each call builds a new stream.
A stream never changes its source, and the source must stay still
Steps like map and filter produce new values and never write into the source list. The other direction matters too: a lambda must not add to or remove from the source, or Java throws ConcurrentModificationException.
Example 5 · The source stays the same; list methods change it
import java.util.ArrayList;import java.util.List;
public class SourceStaysDemo { public static void main(String[] args) { List<Integer> fees = new ArrayList<>(List.of(1200, 0, 4500, 0));
List<Integer> withFine = fees.stream() .filter(f -> f > 0) .map(f -> f + 100) .toList(); System.out.println("Stream result: " + withFine); System.out.println("Source: " + fees);
fees.removeIf(f -> f == 0); fees.replaceAll(f -> f + 100); System.out.println("After removeIf and replaceAll: " + fees); }}Stream result: [1300, 4600] Source: [1200, 0, 4500, 0] After removeIf and replaceAll: [1300, 4600]
What this code does
- The pipeline builds a new list,
withFine. The sourcefeesstill holds all four values, zeros included. - When the list itself must change,
removeIfandreplaceAlldo it in place. Use them after the stream, never from inside its lambdas.
Example 6 · Mistake: changing the source inside a lambda
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class ChangeSourceDemo { public static void main(String[] args) { List<String> trip = new ArrayList<>(List.of("Aarav", "Kabir", "Meera"));
try { trip.stream().forEach(n -> { if (n.startsWith("K")) { trip.add(n + " (guest)"); } }); } catch (ConcurrentModificationException e) { System.out.println("Error: " + e.getClass().getSimpleName()); } System.out.println("List after the error: " + trip);
List<String> fixed = new ArrayList<>(List.of("Aarav", "Kabir", "Meera")); List<String> guests = fixed.stream() .filter(n -> n.startsWith("K")) .map(n -> n + " (guest)") .toList(); fixed.addAll(guests); System.out.println("Fixed: " + fixed); }}Error: ConcurrentModificationException List after the error: [Aarav, Kabir, Meera, Kabir (guest)] Fixed: [Aarav, Kabir, Meera, Kabir (guest)]
What this code does
- The lambda adds to
tripwhile the stream is reading it. Java detects the change and throwsConcurrentModificationException, yet the guest was already added, so the list is left half-changed. - The fix builds the new elements with a separate pipeline and adds them only after it has finished.
list.removeIf(test) removes every element that passes the test, and list.replaceAll(f) replaces each element with f applied to it. Or simply keep the new list the stream built.
That exception is Java's error for "this collection was changed while being walked through". Removing can even crash with a NullPointerException first, because the list shifts under the stream. Despite the word "concurrent", no threads are needed for this error.
Next step
Check your understanding
12 quick questions