在JAVA 8的Stream方法中,流是不能复用的,只要调用了终端操作比如: foreach
、 anyMatch
等,Stream就会自动关闭,如果再次调用,将会提示如下错误:
java.lang.IllegalStateException: streamhasalreadybeenoperateduponorclosedatjava.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229) atjava.util.stream.ReferencePipeline.reduce(ReferencePipeline.java:479) atcom.mirana.stream.FlatMapReduceTest.testFlatMap(FlatMapReduceTest.java:49) atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod) atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) atjava.lang.reflect.Method.invoke(Method.java:498)
如果需要复用流(比如重复代码过多需要抽出公共方法),那么可以使用 Supplier
函数来实现:
publicclassTest { publicstaticvoidmain(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)); } }
输出;
truetrue