Why is this java Stream operated upon twice?

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

Leave a Comment