Reuse Stream in Java 8

When using Java threads in a project, I tried to reuse the thread as such.

I'll start with a set of objects, then do some filtering.

Collection<MyClass> collection = /* form the collection */; Stream<MyClass> myStream = collection.stream().filter(/* some filter */); 

Then I want to reuse the same thread several times. For example, at first I want to just get the first element from the stream, as such.

 MyClass first = myStream.findFirst().get(); 

Then I do some other things, and later I want to use the filtered myStream to perform operations on each object in the stream.

 myStream.forEach(/* do stuff */); 

However, when I try to do this, I get this error.

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

I can solve the problem by doing one of the following:

  • Create a new stream from the source collection and filter it again
  • Collect the stream into a filtered collection, then create the stream on

So, I think there are several questions that I based on my findings.

  • If you cannot reuse streams, then when will it ever be useful to return a stream instance for later use?
  • Is it possible to clone threads so that they can be reused without raising an IllegalStateException ?
+5
source share
1 answer

If you cannot reuse streams, then when will it ever be useful to return a stream instance for later use?

If you have a method that returns a stream, and you need this stream to do two things, just call the method two times and get two different threads.

Is it possible to clone streams so that they can be reused without raising an IllegalStateException?

Lambda expressions make it easy to configure the Supplier<Stream> , so you don't have to rebuild it. This may be redundant if all you do is a single .filter , but for more complex stream settings that are too local to guarantee a method, this is a good option:

 Supplier<Stream<MyClass>> sup = () -> collection.stream().....; / first = sup.get().findFirst().get(); // do one thing sup.get().forEach(...); // do another thing 
+6
source

All Articles