Stream has already been operated upon or closed Exception in Java 8

“Stream has already been operated upon or closed” is a exception that we may happen when working with the Stream class in Java 8. In this post, we’ll discover the scenarios when this exception occurs, and how to avoid it via practical examples.

Stream is closed

We are consedering the below example which produce this exception:

Run this program and encounter the output like this

Stream has already been operated upon or closed

Noticed that we’re allowed to do a single operation that consumes a Stream. Because the operation is finished on a Stream object. This object is consumed and closed. This is the reason why we encounter the above exception.

Reuse a stream
Simply, we can create a new Stream each time we need to reuse it. Of course, we can do that manually, but we should use Supplier function interface for that.

Here is the program that uses Supplier function interface.

Output

That’s all about the “Stream has already been operated upon or closed” post.

References
Supplier JavaDoc

Download the complete source code, click link below

Java8StreamClosedExample.zip (2 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons