Collectors.counting()
A counting collector, usually used inside `groupingBy()`.
Available since: Java 8
Syntax
static <T> Collector<T, ?, Long> counting()Return value
Collector<T, ?, Long>A collector that counts elements.
Examples
The frequency of every word:
void main() {
Map<String, Long> freq = Stream.of("yes", "no", "yes", "maybe", "yes", "no")
.collect(Collectors.groupingBy(w -> w, TreeMap::new, Collectors.counting()));
IO.println(freq);
}Output:
{maybe=1, no=2, yes=3}Notes
The result type is Long, so the map becomes Map<String, Long>. On its own, count() is simpler than collect(counting()).
See also
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- Stream.count() — Counts the elements of a stream.
- Collections.frequency() — Counts how many times an element occurs in a collection.
Related recipes
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.