Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
那么为什么会抛出以下代码:
java.lang.IllegalStateException: stream has already been operated upon or closed
Stream<Integer> stream = Stream.of(1,2,3);
stream.filter( x-> x>1 );
stream.filter( x-> x>2 ).forEach(System.out::print);
API 的第一个过滤操作不应该对 Stream 进行操作。
最佳答案
这是因为您忽略了 filter
的返回值。
Stream<Integer> stream = Stream.of(1,2,3);
stream.filter( x-> x>1 ); // <-- ignoring the return value here
stream.filter( x-> x>2 ).forEach(System.out::print);
Stream.filter
返回一个 new Stream
,其中包含与给定谓词匹配的该流的元素。但重要的是要注意它是一个新的 Stream。旧的过滤器添加到它时已对其进行了操作。但新的不是。
引自 Stream
Javadoc:
A stream should be operated on (invoking an intermediate or terminal stream operation) only once.
在这种情况下,filter
是对旧 Stream 实例进行操作的中间操作。
所以这段代码可以正常工作:
Stream<Integer> stream = Stream.of(1,2,3);
stream = stream.filter( x-> x>1 ); // <-- NOT ignoring the return value here
stream.filter( x-> x>2 ).forEach(System.out::print);
正如 Brian Goetz 所说,您通常会将这些调用链接在一起:
Stream.of(1,2,3).filter( x-> x>1 )
.filter( x-> x>2 )
.forEach(System.out::print);
关于java - 为什么这个 java Stream 被操作了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677708/