I’m not sure if there is already a rule which checks that. I have found only three rules which contain the word ‘terminal’ (Streams without terminal, Streams using peek()
and consumed Streams).
Description
The value returned by terminal operations of java.util.stream.Stream
should not be ignored. Similar to S2201 it is pointless and a waste of resources to construct a stream, process it and immediatly throw away the result.
Type: Code Smell
Non-compliant Code
list.stream().filter(criteria).collect(toList());
list.stream().anyMatch(criteria);
Compliant Code
var filteredList = list.stream().filter(criteria).collect(toList());
var hasMatch = list.stream().anyMatch(criteria);
Exceptions
Intermediate operations which can have side effects should be exempt. Technically, most intermediates can have side effects, but only calls to map()
/flatMap()
, their variants which map to primitives and peek()
should be exempt. Using filter()
with side effects is a different bug/codesmell.