Card 07/ 10
All 10 cards
GotchaDifficulty: Advanced1 min
Why You Cannot Use a Stream Twice
A stream stored in a variable so it can be counted and then collected. The second use throws, and the message is about a state nobody set.
Stream<Invoice> big = invoices.stream().filter(i -> i.pence() > 10_000);
long howMany = big.count();
List<Invoice> list = big.toList();Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closedA stream is not a collection. It does not hold the elements — it holds a way of pulling them from a source, and once the terminal operation has pulled them the stream has nothing left to give.
That is exactly why the source can be a file, a network response or an infinite generator. A thing that could be replayed would have to remember everything it produced.
| You want | Do |
|---|---|
| Two results from one pass | Collect once, then work on the collection |
| Two independent pipelines | Call .stream() on the source twice |
| A count and the elements | Collect to a list and call size() |
The habit that avoids all of it: do not store a stream in a variable. Build it, use it and end it in one expression, and the question never comes up.