Course contentsShow
← Java
Lesson 1396 of 2,87031. Streams API: Creation and BasicsFree lesson

Streams Are Single-Use: Terminal Operations Consume Them

Learn that once a terminal operation executes, the stream is consumed and cannot be reused or re-traversed.

Streams Are Single-Use: Terminal Operations Consume Them

You'll learn why a stream can only be used once and what happens when you try to reuse it.

The Single-Use Nature of Streams

Once you execute a terminal operation on a stream, that stream is consumed and cannot be reused or re-traversed. Think of a stream like a conveyor belt in a factory: once the items have moved through and been packaged (terminal operation), you can't send those same items back through the belt again. The pipeline has completed its work and is shut down.

This is a fundamental characteristic that distinguishes streams from collections. A List can be iterated over repeatedly, but a Stream is a one-time-use data pipeline.

What Happens When You Try to Reuse

If you attempt to perform another operation (intermediate or terminal) on an already-consumed stream, Java throws an IllegalStateException with a message like "stream has already been operated upon or closed."

List<String> names = List.of("Alice", "Bob", "Charlie");
Stream<String> stream = names.stream();

long count = stream.count(); // Terminal operation - stream consumed
// count is now 3

// Attempting to reuse the consumed stream:
stream.forEach(System.out::println); // IllegalStateException!

The Solution

If you need to perform multiple terminal operations, create a new stream each time:

List<String> names = List.of("Alice", "Bob", "Charlie");

long count = names.stream().count(); // First stream

names.stream().forEach(System.out::println); // Second, fresh stream

Key Takeaway: Streams are single-use pipelines—once a terminal operation executes, the stream is consumed and cannot be reused. Create a new stream if you need to perform additional operations.