Java 8 IllegalStateException “Stream has already been operated upon or closed” Exception (Stream reuse)


Quick fix to "Stream has already been operated upon or closed" problem in Java 8. This happens if the stream is already consumed and closed.

1. Overview

In this short tutorial, We'll see the most common exception "java.lang.IllegalStateException: stream has already been operated upon or closed". We may encounter this exception when working with the Stream interface in Java 8.

Can we collect stream twice after closing?
Java Stream reuse – traverse stream multiple times?

stream has already been operated upon or closed


java.lang.IllegalStateException: stream has already been operated upon or closed

2. Look At Problem

2.1 From Java 8 API:

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

2.2 Explanation:

Taking a deeper look at what happens after stream creation.

A) Stream has intermediate operations, short-circuiting terminal operation and terminal operations.
B) Once a Stream is created, A pipe lines associated to this stream will be created.
C) On the stream, We can perform operations like filter(), map(), findAny(), findFirst(), count(), sum() methods on it.
D) Once we perform any operation on the stream, then that operation is placed into the current stream.
E) All operations will be executed and closes stream.

filter(), map() methods are intermediate operations.
findAny(), findFirst() are short-circuiting terminal operation
count() and sum() are terminal operations.

2.3 Example 1:

Next, think if we create a substreams from main stream as below.

String conent = "line 1 \n line 2 \\n line 3 \\n line 4 \\n line 5";

Here a stream is created with pipeline.

Stream mainStream = Stream.of(conent.split("\n"));

Now, calling filter method on mainStream. Now filter operation is placed in the current pipeline.

mainStream.filter(line -> line.indexOf("line") > -1);

Now again calling filter method on mainStream. That will try to put the filter operation in the pipe line. But the pipe line is currently in operated mode with above filter. So, it it not possible to create another pipe line on the same stream.

mainStream.filter(line -> line.indexOf("1") > -1);

So it will throw now Runtime exception.

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
 at java.base/java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
 at java.base/java.util.stream.ReferencePipeline.(ReferencePipeline.java:94)
 at java.base/java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:696)
 at java.base/java.util.stream.ReferencePipeline$2.(ReferencePipeline.java:165)
 at java.base/java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:164)
 at com.java.w3schools.blog.exceptions.streams.StreamIntermediateException.main(StreamIntermediateException.java:17)

2.4 Example 2:

Another example program to produce the same exception.

// Creating Stream from String.
String conent = "line 1 \n line 2 \\n line 3 \\n line 4 \\n line 5";
Stream mainStream = Stream.of(conent.split("\n"));

// Operation on mainStream 
Optional firstValue = mainStream.findFirst();
System.out.println("firstValue : " + firstValue.get());

// Operation on mainStream

Optional anyValue = mainStream.findAny();
System.out.println("anyValue : " + anyValue.get());

See in this example, calling two methods on mainStream.

First when calling findFirst() then it returns value. But next invoking findAny(), at this time stream or pipe line is already closed. So it can not perform operation on the same stream.


firstValue : line 1 
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
 at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
 at java.base/java.util.stream.ReferencePipeline.findAny(ReferencePipeline.java:548)
 at com.java.w3schools.blog.exceptions.streams.StreamCloseException.main(StreamCloseException.java:25)

Here firstValue is printed but while getting value from findAny() operation it has failed to get the stream because stream is already closed.


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.

3. Solutions

We have many scenarios where the same stream is required to perform many operations. See the above example 2 where two values are needed.

To solve this issue, We need to create two-stream instances for these two separate operations.


Instead of creating two stream objects separately, We can use built in API Functional Interface Supplier<T> which is super handy in usage.

Supplier> supplier = () -> Stream.of(conent.split("\n"));

// findFirst Operation
Optional firstValue = supplier.get().findFirst();
System.out.println("firstValue : " + firstValue.get());

// findAny Operation
Optional anyValue =supplier.get().findAny();
System.out.println("anyValue : " + anyValue.get());

In this program, created a Supplier object with type of Stream<String>. Supplier has a abstract method that is get() which returns Stream<String>. Now, We have to use Lambda Expression for Supplier Functional Interface with () zero arguments.

So, Whenever we call supplier.get() method than a new fresh Stream<String> object will be created and can perform any stream operation on it.


Output is returned properly without any errors.

firstValue : line 1 
anyValue : line 5

4. Conclusion

In this article, We've seen how to fix "java.lang.IllegalStateException: stream has already been operated upon or closed" problem when working with Java 8 Stream objects.

And also seen how to use terminal operations on the same stream using Supplier interface which avoids famous exception "stream has already been operated upon or closed".

All the examples shown in this article are available over GitHub with complete examples.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java 8 IllegalStateException “Stream has already been operated upon or closed” Exception (Stream reuse)
Java 8 IllegalStateException “Stream has already been operated upon or closed” Exception (Stream reuse)
Quick fix to "Stream has already been operated upon or closed" problem in Java 8. This happens if the stream is already consumed and closed.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content