00:00

Collectors.counting() in Java

Last updated:

Collectors.counting() is a static method of java.util.stream.Collectors, available since Java 8, that returns a Collector which counts the elements it receives and produces a Long. On its own it does the same as the terminal operation count(); its real value is as a downstream collector, for counting per group.

This tutorial covers its signature, counting per key with groupingBy() and partitioningBy(), sorting by counts, and how it differs from Stream.count().

1. Syntax and Method Signature

Collectors.java (API)
// java.util.stream.Collectors (Java 8)
static <T> Collector<T, ?, Long> counting()

The result type is the wrapper Long, because collectors produce objects. If no elements are counted, the result is 0L.

Usage
Map<String, Long> ordersPerCity = orders.stream()
        .collect(Collectors.groupingBy(Order::city, Collectors.counting()));

2. How counting() Works

counting() is defined as a summing collector that adds 1L per element. Used inside groupingBy(), it keeps only a running count per group instead of a list, so it uses very little memory even for huge streams.

Unlike Stream.count(), which may skip work when the size is known, a collector always receives every element that reaches it.

counting() as a downstream collector Visits to pages home, cart, home, product, home and cart are grouped by page. counting turns each group into a number: home 3, cart 2, product 1. GROUP ELEMENTS counting() home home 3 visits 3 cart cart 2 visits 2 product product 1 visit 1
Figure 1: groupingBy() creates the groups and counting() reduces each one to a Long. Only the counts are kept, not the elements.

3. Java Examples

Example 1: Word frequency

Count how often each word appears in a short product review.

WordFrequency.java
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class WordFrequency {

    public static void main(String[] args) {
        String review = "good battery good screen average camera good price";

        Map<String, Long> frequency = Arrays.stream(review.split(" "))
                .collect(Collectors.groupingBy(word -> word, TreeMap::new, Collectors.counting()));

        System.out.println(frequency);
    }
}
Output
{average=1, battery=1, camera=1, good=3, price=1, screen=1}

How it works: Each distinct word becomes a key and counting() stores how often it occurred. See Element Frequency for more frequency patterns.

Example 2: Counting per category of objects (Java 16+)

Count support tickets per priority for a dashboard tile.

TicketsPerPriority.java
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TicketsPerPriority {

    enum Priority { LOW, MEDIUM, HIGH, CRITICAL }

    record Ticket(int id, Priority priority) { }

    public static void main(String[] args) {
        List<Ticket> tickets = List.of(
                new Ticket(1, Priority.HIGH), new Ticket(2, Priority.LOW), new Ticket(3, Priority.HIGH),
                new Ticket(4, Priority.CRITICAL), new Ticket(5, Priority.LOW), new Ticket(6, Priority.HIGH));

        Map<Priority, Long> perPriority = tickets.stream()
                .collect(Collectors.groupingBy(Ticket::priority,
                        () -> new EnumMap<>(Priority.class), Collectors.counting()));

        System.out.println(perPriority);
    }
}
Output
{LOW=2, HIGH=3, CRITICAL=1}

How it works: An EnumMap keeps the keys in the enum's declaration order. MEDIUM does not appear because no ticket has it; groupingBy() only creates keys that occur.

Example 3: The most common value (Java 10+)

Find the most frequently ordered dish.

MostOrderedDish.java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MostOrderedDish {

    public static void main(String[] args) {
        List<String> orders = List.of("dosa", "idli", "dosa", "vada", "dosa", "idli");

        Map.Entry<String, Long> top = orders.stream()
                .collect(Collectors.groupingBy(dish -> dish, Collectors.counting()))
                .entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .orElseThrow();

        System.out.println("Most ordered: " + top.getKey() + " (" + top.getValue() + " times)");
    }
}
Output
Most ordered: dosa (3 times)

How it works: First count per dish, then stream the map's entries and take the entry with the largest value. On a tie, add a second comparator for a stable answer.

Example 4: counting() compared with count() (Java 9+)

Count the same filtered stream with the collector and with the terminal operation.

CountingVsCount.java
import java.util.List;
import java.util.stream.Collectors;

public class CountingVsCount {

    public static void main(String[] args) {
        List<Integer> amounts = List.of(250, 1200, 80, 3400, 640);

        Long viaCollector = amounts.stream().filter(a -> a > 500).collect(Collectors.counting());
        long viaCount = amounts.stream().filter(a -> a > 500).count();

        System.out.println("counting(): " + viaCollector);
        System.out.println("count():    " + viaCount);
    }
}
Output
counting(): 3
count():    3

How it works: Both give the same number. For a single total, count() is shorter and returns a primitive long; use counting() inside other collectors.

4. Real-World Use Cases

  • Analytics: page views per page, orders per city, errors per code.
  • Dashboards: open tickets per priority or per assignee.
  • Data quality: count records per status to find unexpected values.
  • Top-n lists: count first, then sort entries by value.

5. Important Points

  • Returns Long, not int or long.
  • Missing keys: groups with zero elements do not appear in a groupingBy() result.
  • Memory efficient: stores one counter per group, not the elements.
  • Null keys are not allowed in groupingBy().
  • Parallel safe through normal collector combining.

6. counting() vs Related Approaches

ApproachResultUse when
stream.count()longOne total for the whole stream
collect(counting())LongRarely on its own
groupingBy(k, counting())Map<K, Long>Counts per key
partitioningBy(p, counting())Map<Boolean, Long>Counts of matches and non-matches
groupingBy(k, summingInt(x -> 1))Map<K, Integer>When you need Integer counts

7. Common Mistakes and Best Practices

Grouping into lists just to count them

Wasteful
Map<String, List<Order>> groups = orders.stream().collect(groupingBy(Order::city));
groups.forEach((city, list) -> System.out.println(city + " " + list.size()));   // stores every order
Better
orders.stream().collect(groupingBy(Order::city, counting()))
      .forEach((city, n) -> System.out.println(city + " " + n));

Expecting zero counts for missing categories

FillMissingCounts.java
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FillMissingCounts {

    enum Status { NEW, ACTIVE, CLOSED }

    public static void main(String[] args) {
        List<Status> statuses = List.of(Status.NEW, Status.NEW, Status.CLOSED);

        Map<Status, Long> counts = new EnumMap<>(Status.class);
        for (Status s : Status.values()) {
            counts.put(s, 0L);
        }
        counts.putAll(statuses.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting())));

        System.out.println(counts);
    }
}
Output
{NEW=2, ACTIVE=0, CLOSED=1}

Other mistakes to avoid

  • Assigning the result to Map<K, Integer>. It is Map<K, Long>.
  • Using counting() for a single total. count() is clearer.
  • Sorting a HashMap result by printing it. Use a TreeMap or sort the entries.

8. Summary

  • counting() is a collector that counts elements into a Long.
  • Its main use is as a downstream collector in groupingBy() and partitioningBy().
  • It stores one counter per group, not the elements.
  • Missing categories do not appear; pre-fill zeros when a report needs them.

9. References