“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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class StreamExample { public static void main(String[] args) { String[] array = { "java", "nodejs", "php" }; Stream<String> myStream = Arrays.stream(array); // loop a stream myStream.forEach(e -> System.out.println(e)); // reuse it to print again! throws IllegalStateException myStream.forEach(e -> System.out.println(e)); } } |
Run this program and encounter the output like this
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class StreamExample2 { public static void main(String[] args) { String[] array = { "java", "nodejs", "php" }; Supplier<Stream<String>> streamSupplier = () -> Stream.of(array); // get new stream via supplier streamSupplier.get().forEach(e -> System.out.println(e)); // get another new stream and print again streamSupplier.get().forEach(e -> System.out.println(e)); } } |
Output
1 2 3 4 5 6 |
java nodejs php java nodejs php |
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 (225 downloads)