Inspectopedia Help

Inefficient Stream API call chains ending with count()

Reports Stream API call chains ending with the count() operation that could be optimized.

The following call chains are replaced by this inspection:

  • In Java 8 actually iterates over the collection elements to count them, while Collection.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() > 0Stream.anyMatch(o -> ...). Unlike the original call, anyMatch() may stop the computation as soon as a matching element is found.

  • Stream.filter(o -> ...).count() == 0Stream.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.

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3


Java, 233.SNAPSHOT

Last modified: 13 July 2023