java - Stream.count() 与 Collectors.counting() 有什么区别

标签 java performance java-stream

count()之间有什么区别吗? Stream 中的方法界面对比 counting()Collectors ?一般应该使用哪一种?使用其中之一是否有任何性能优势?

最佳答案

一个区别在于实现。这记录在 Stream.count() (至少在版本 9+ 上):

An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source. In such cases no source elements will be traversed and no intermediate operations will be evaluated...


尝试这个:
System.out.println(Stream.of(1, 2, 3, 4, 5)
        .map(i -> {
            System.out.println("processing " + i);
            return i * 2;
        }).count());

System.out.println(Stream.of(1, 2, 3, 4, 5)
        .map(i -> {
            System.out.println("processing " + i);
            return i * 2;
        }).collect(Collectors.counting()));
两者都会给你正确的计数,但第一个可能会跳过 map() 的执行,因此可能不会显示 println的输出。如文档所述,这是实现细节(count() 如果可以在不执行管道的情况下确定元素数量,则可以跳过中间操作)

关于java - Stream.count() 与 Collectors.counting() 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68017820/

相关文章:

java - Do-While 循环中的异常线程

c# - 如何使用 LINQ 更改多个对象中的相同属性?

java - 如何使用 java 流比较两个 ArrayList 并使用过滤器获取 list1

java - Java中的有限生成流-如何创建一个?

Java:使用 Stream API 从原始数组创建列表

java - Hibernate 非主键列的级联更新

java - SwingUtilities.InvokeLater 和 ButtonListeners

Java - 制作对象时,它们应该放在代码的什么位置

c++ - 解包 std::reference_wrapper 的成本

c - 关于交换循环的性能问题