Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

Related recipes

In the tutorial

  • Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.

Thanks for reading!

Donate to the site — we work hard for you.