为什么这个java Stream会运行两次? [英] Why is this java Stream operated upon twice?

查看:232
本文介绍了为什么这个java Stream会运行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8 API 说:


在执行管道的终端操作之前,管道源的遍历不会开始。

Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

那么为什么下面的代码抛出:

So why the following code throws :


java.lang.IllegalStateException:stream已经已经按
或关闭操作

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上运行。

The first filtering operation according to the API is not supposed to operate on the Stream.

推荐答案

这是因为您忽略了过滤器的返回值。

This happens because you are ignoring the return value of 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.filter returns a new Stream consisting of the elements of this stream that match the given predicate. But it's important to note that it's a new Stream. The old one has been operated upon when the filter was added to it. But the new one wasn't.

引自 Stream Javadoc:

Quoting from Stream Javadoc:


流应该只对(调用中间或终端流操作)进行一次操作。

A stream should be operated on (invoking an intermediate or terminal stream operation) only once.

在这种情况下,过滤器是在旧的Stream实例上运行的中间操作。

In this case, filter is the intermediate operation that operated on the old Stream instance.

所以这段代码可以正常工作:

So this code will work fine:

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所说,你通常会链那些一起打电话:


As noted by Brian Goetz, you would commonly chain those calls together:

Stream.of(1,2,3).filter( x-> x>1 )
                .filter( x-> x>2 )
                .forEach(System.out::print);

这篇关于为什么这个java Stream会运行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆