Inefficient Stream API call chains ending with count()
Reports Stream API call chains ending with a count() operation, that are optimizable.
The following call chains can be replaced by this inspection:
Collection.stream().count()→Collection.size(). In Java 8Collection.stream().count()actually iterates over the collection elements to count them, whileCollection.size()is much faster for most of the collections.Stream.flatMap(Collection::stream).count()→Stream.mapToLong(Collection::size).sum(). Similarly, there's no need to iterate over all the nested collections. Instead, their sizes could be summed up.Stream.filter(o -> ...).count() > 0→Stream.anyMatch(o -> ...). Unlike the original call,anyMatch()may stop the computation as soon as a matching element is found.Stream.filter(o -> ...).count() == 0→Stream.noneMatch(o -> ...). Similar to the above.
Note that if the replacement involves a short-circuiting operation like anyMatch(), there could be a visible behavior change, if the intermediate stream operations produce side effects. In general, side effects should be avoided in Stream API calls.
Locating this inspection
- By ID
Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.
ReplaceInefficientStreamCount- Via Settings dialog
Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.
This inspection depends on the Java feature 'Stream and Optional API', which is available since Java 8.
Suppressing Inspection
You can suppress this inspection by placing the following comment marker before the code fragment where you no longer want messages from this inspection to appear:
More detailed instructions as well as other ways and options that you have can be found in the product documentation:
Inspection Details | |
|---|---|
By default bundled with: |