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/