Streams Are Consumed Once
You'll learn: Why attempting to reuse a Java stream after traversal throws an exception and how to handle this constraint.
The Core Idea
Unlike collections, which you can iterate over repeatedly, a stream can only be traversed once. After a terminal operation completes, the stream is considered "consumed" or "closed." If you try to invoke any operation on that same stream instance again, Java throws an IllegalStateException.
Think of a stream like a conveyor belt in a factory: once the items have passed through and been processed, you can't rewind the belt and process them again. You'd need to start a new conveyor belt (create a new stream) from the original source.
Why This Restriction Exists
Streams are designed for single-pass processing. They don't store data—they pull elements from a source, transform them through intermediate operations, and deliver results via a terminal operation. Allowing reuse would require caching all elements, defeating the efficiency and lazy-evaluation benefits streams provide.
Practical Implications
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> stream = names.stream();
long count = stream.count(); // Terminal operation
// stream is now consumed
stream.forEach(System.out::println); // IllegalStateException!
The second operation fails because count() already consumed the stream. To process the data again, create a new stream:
names.stream().count();
names.stream().forEach(System.out::println); // Works fine
This isn't wasteful—the original collection remains intact, and creating streams is lightweight.
Key Takeaway:
A stream can only be traversed once; after a terminal operation, you must create a new stream from the source to perform additional operations.