In Java 8, the stream cannot be reused, and once it is used or consumed, the stream is closed. 1. Example–stream has been closed!
Looking at the example below, it will be thrown a illegalstateexception that says "stream is closed". Testjava8.java
Package com.mkyong.java8;
Import Java.util.Arrays;
Import Java.util.stream.Stream;
public class TestJava8 {public
static void Main (string[] args) {
string[] array = {"A", "B", "C", "D", "E"};
stream<string> stream = Arrays.stream (array);
Loop a stream
Stream.foreach (x-> System.out.println (x));
Reuse it to filter again! Throws IllegalStateException
Long Count = Stream.filter (x-> "B". Equals (x)). Count ();
System.out.println (count);
}
}
Output
Java.lang.IllegalStateException:stream has already been operated upon or closed at Java.util.stream.AbstractPipeline. (abstractpipeline.java:203) at Java.util.stream.ReferencePipeline. (referencepipeline.java:94) at Java.util.stream.referencepipeline$statelessop. (referencepipeline.java:618) at java.util.stream.referencepipeline$2. (referencepipeline.java:163) at Java.util.stream.ReferencePipeline.filter (referencepipeline.java:162) at Com.hostingcompass.whois.range.run.TestJava8.main (TESTJAVA8.JAVA:25) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) at Sun.reflect.NativeMethodAccessorImpl.invoke ( nativemethodaccessorimpl.java:62) at Sun.reflect.DelegatingMethodAccessorImpl.invoke ( delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (method.java:498) at Com.intellij.rt.execution.application.AppMain.main (appmain.java:144)
2. example– to use a stream again
Whatever the reason, you really want to reuse a stream, you can use the following method: Testjava8.java
Package com.mkyong.java8;
Import Java.util.function.Supplier;
Import Java.util.stream.Stream;
public class TestJava8 {public
static void Main (string[] args) {
string[] array = {"A", "B", "C", "D", "E"};
Supplier<stream<string>> streamsupplier = ()-> stream.of (array);
Get new stream
Streamsupplier.get (). ForEach (x-> System.out.println (x));
Get another new stream
long Count = Streamsupplier.get (). Filter (x-> "B". Equals (x)). Count ();
System.out.println (count);
}
}
Output
A
b
c
d
e
1
Each get () returns a new stream.