Let's imagine the following code:
Stream<Integer> numberStream = ...;
Predicate<Integer> isEven = ...;
Predicate<Integer> isOdd = ...;
List<Integer> evenNumbers = numberStream
.filter(isEven)
.collect(Collectors.toList());
List<Integer> oddNumbers = numberStream
.filter(isOdd)
.collect(Collectors.toList()); // this line will throw IllegalStateException
The above code compiles without any warnings. However, trying to run it will always result in an IllegalStateException
.
After looking into it, I found out that one Stream
can only have one terminal operation, so basically there is no point in storing it inside a variable.
It seems to me that this would be a very easy error to spot by the compiler. Why does it compile without errors? Is there some use case where code like that would be useful?