$show=/label

“Stream has already been operated upon or closed” Exception in Java

SHARE:

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.



stream has already been operated upon or closed

Exception

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.


Output:

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.

Note:

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.


Note:

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:

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.

References for various examples


COMMENTS

BLOGGER

About Us

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

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,71,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,47,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,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,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,2,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,7,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: “Stream has already been operated upon or closed” Exception in Java
“Stream has already been operated upon or closed” Exception in Java
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.
https://1.bp.blogspot.com/-7jjCElA9-sE/XQtJFxgMJ1I/AAAAAAAABr4/cAnm4YFqdT0wvVgNMStSZaaF3cZMKd7EQCLcBGAs/s640/stream%2Bhas%2Balready%2Bbeen%2Boperated%2Bupon%2Bor%2Bclosed.PNG
https://1.bp.blogspot.com/-7jjCElA9-sE/XQtJFxgMJ1I/AAAAAAAABr4/cAnm4YFqdT0wvVgNMStSZaaF3cZMKd7EQCLcBGAs/s72-c/stream%2Bhas%2Balready%2Bbeen%2Boperated%2Bupon%2Bor%2Bclosed.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/06/java-stream-operated-upon-or-closed-exception.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/06/java-stream-operated-upon-or-closed-exception.html
true
3124782013468838591
UTF-8
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