count() 运算结束的 Stream API 调用链。
以下调用链可被替换为此检查:
Collection.stream().count() → Collection.size(). 在 Java 8 中,Collection.stream().count() 实际上是通过迭代集合元素来进行计数,而 Collection.size() 对于大多数集合来说速度要快得多。Stream.flatMap(Collection::stream).count() → Stream.mapToLong(Collection::size).sum(). 同样,不需要遍历所有嵌套集合。 相反,它们的大小可以相加。Stream.filter(o -> ...).count() > 0 → Stream.anyMatch(o -> ...). 与初始调用不同,一旦找到匹配元素后 anyMatch() 就可以立即停止计算。Stream.filter(o -> ...).count() == 0 → Stream.noneMatch(o -> ...). 与以上相似。
请注意,如果替换涉及 anyMatch() 等短路操作,那么中间流操作产生副作用时,可能会出现明显的行为变化。 在 Stream API 调用中通常应避免副作用。