CKTIS / Java
Collectors.counting: practical reference
Collectors.counting: practical reference: Collectors.counting returns a collector equivalent to reducing every element to 1L and summing, so its result type is Long.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Collectors.counting(...)Collectors.counting returns a collector equivalent to reducing every element to 1L and summing, so its result type is Long.
Use it as a downstream collector in groupingBy or partitioningBy when each group needs only its cardinality.
It counts elements, including null elements accepted by the upstream stream; it does not count distinct values unless distinct() is applied first.
An empty stream yields 0L. Extremely large streams can overflow long because the contract does not provide arbitrary-precision counting.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
long count = java.util.stream.Stream.of("a", "b", "c")
.collect(java.util.stream.Collectors.counting());
System.out.println(count);
}
}
Result
3
The example exercises the documented element in a small deterministic program and compares exact standard output.