Java8 复用stream对象

在JAVA 8的Stream方法中,是不能复用的,只要调用了终端操作比如: foreachanyMatch等,Stream就会自动关闭,如果再次调用,将会提示如下错误:

java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
at java.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:479)
at com.mirana.stream.FlatMapReduceTest.testFlatMap(FlatMapReduceTest.java:49)
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)

如果需要复用(比如重复代码过多需要抽出公共方法),那么可以使用 Supplier函数来实现:

public class Test {
public static void main(String[] args) {
List<Integer> data = Arrays.asList(3, 2, 11, 3, 1, 1);
Supplier<Stream<Integer>> streamSupplier = () -> data.stream().filter(e -> e < 5);
System.out.println(streamSupplier.get().anyMatch(e -> e == 1));
System.out.println(streamSupplier.get().noneMatch(e -> e > 6));
}
}

输出;

true
true