Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

Why is this java Stream operated upon twice?

The Java 8 API says:

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 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);

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

Quoting from Stream Javadoc:

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

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);

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...