My understanding was that a Java 8 Stream is considered to be consumed once a terminal operation, such as forEach() or count(), is performed.
However, the test case multipleFilters_separate below throws an IllegalStateException even though filter is a lazy intermediate operation, just called as two statements. And yet, I can chain the two filter operations into a single statement and it works.
@Test(expected=IllegalStateException.class)
public void multipleFilters_separate() {
Stream<Double> ints = Stream.of(1.1, 2.2, 3.3);
ints.filter(d -> d > 1.3);
ints.filter(d -> d > 2.3).forEach(System.out::println);
}
@Test
public void multipleFilters_piped() {
Stream<Double> ints = Stream.of(1.1, 2.2, 3.3);
ints.filter(d -> d > 1.3)
.filter(d -> d > 2.3)
.forEach(System.out::println);
}
From this, I'm assuming a Stream is considered to be consumed after the first statement that uses it whether that statement calls a terminal operation or not. Does that sound right?