Collectors.counting() in Java
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
// 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.
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.
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.
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);
}
}
{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.
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);
}
}
{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.
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)");
}
}
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.
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);
}
}
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, notintorlong. - 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
| Approach | Result | Use when |
|---|---|---|
stream.count() | long | One total for the whole stream |
collect(counting()) | Long | Rarely 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
Map<String, List<Order>> groups = orders.stream().collect(groupingBy(Order::city));
groups.forEach((city, list) -> System.out.println(city + " " + list.size())); // stores every order
orders.stream().collect(groupingBy(Order::city, counting()))
.forEach((city, n) -> System.out.println(city + " " + n));
Expecting zero counts for missing categories
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);
}
}
{NEW=2, ACTIVE=0, CLOSED=1}
Other mistakes to avoid
- Assigning the result to
Map<K, Integer>. It isMap<K, Long>. - Using
counting()for a single total.count()is clearer. - Sorting a
HashMapresult by printing it. Use aTreeMapor sort the entries.
8. Summary
counting()is a collector that counts elements into aLong.- Its main use is as a downstream collector in
groupingBy()andpartitioningBy(). - It stores one counter per group, not the elements.
- Missing categories do not appear; pre-fill zeros when a report needs them.
9. References
Frequently Asked Questions (FAQ)
Q1. What does Collectors.counting() return?
It returns a collector that produces a Long with the number of elements it received. For an empty input the result is 0.
Q2. How do I count occurrences of each element in a list?
Use list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())). The result maps each distinct element to its count.
Q3. What is the difference between count() and Collectors.counting()?
count() is a terminal operation that returns a primitive long for the whole stream. counting() is a collector, mainly used as a downstream collector inside groupingBy() or partitioningBy() to count per group.
Q4. Why is the count a Long and not an int?
Collectors return objects, and counts can exceed the int range, so counting() produces a Long. Use summingInt(e -> 1) if you need Integer values.
Q5. Why are some categories missing from my counts?
groupingBy() only creates keys for values that occur in the data. Pre-fill a map with zeros for every category, then merge in the counts.