Stream.count() 和 Collectors.counting() 有什么区别
What is the difference between Stream.count() vs Collectors.counting()
Stream
接口中的 count()
方法与 Collectors
中的 counting()
方法有什么区别吗?一般应该使用哪一种?使用一个比另一个有任何性能优势吗?
如果要计算(所有)stream 个元素,请使用 count()
Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();
需要对计数进行分组时使用,如:
Map<String, Long> collect =
wordsList.stream().collect(groupingBy(Function.identity(), counting()));
一个区别在于实现。这记录在 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()
可以跳过中间操作,如果它可以在不执行管道的情况下确定元素的数量)
// creating a stream of strings
Stream<String> s = Stream.of("1", "2", "3", "4");
// using Collectors counting() method to
// count the number of input elements
long ans = s.collect(Collectors.counting());
// displaying the required count
System.out.println(ans);
Stream
接口中的 count()
方法与 Collectors
中的 counting()
方法有什么区别吗?一般应该使用哪一种?使用一个比另一个有任何性能优势吗?
如果要计算(所有)stream 个元素,请使用 count()
Returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();
需要对计数进行分组时使用
Map<String, Long> collect = wordsList.stream().collect(groupingBy(Function.identity(), counting()));
一个区别在于实现。这记录在 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()
可以跳过中间操作,如果它可以在不执行管道的情况下确定元素的数量)
// creating a stream of strings
Stream<String> s = Stream.of("1", "2", "3", "4");
// using Collectors counting() method to
// count the number of input elements
long ans = s.collect(Collectors.counting());
// displaying the required count
System.out.println(ans);