Java Streams learning path Level 1 This level · 3 of 25
Easy java streams

Can a Stream be reused?

The 30 second answer

No. Once you invoke an intermediate or terminal operation, that stream is consumed. Reusing it throws IllegalStateException saying it has already been operated upon or closed. The fix is to re-stream the collection or wrap stream creation in a Supplier.

Could you say this in an interview?

No. "A stream should be operated on (invoking an intermediate or terminal stream operation) only once." Reuse throws IllegalStateException ("stream has already been operated upon or closed").

Fix: use a Supplier<Stream<T>> or re-stream the collection.

Sources (1)
  1. Stream class descriptiondocs.oracle.com
Previous
Next