Is there any way to reuse a Stream?

Francisco picture Francisco · Mar 28, 2016 · Viewed 40.1k times · Source

I'm learning the new Java 8 features, and while experimenting with streams (java.util.stream.Stream) and collectors, I realized that a stream can't be used twice.

Is there any way to reuse it?

Answer

Dioxin picture Dioxin · Mar 28, 2016

From the documentation:

A stream should be operated on (invoking an intermediate or terminal stream operation) only once.

A stream implementation may throw IllegalStateException if it detects that the stream is being reused.

So the answer is no, streams are not meant to be reused.