Count Element Frequency Using Java Streams
Counting the frequency of elements means building a map from each distinct value to the number of times it occurs. With Java streams (Java 8+) the standard solution is collect(Collectors.groupingBy(Function.identity(), Collectors.counting())), often followed by sorting the entries to find the most or least common values.
This page covers word frequency, character frequency, frequency of object properties, the most common values, and an alternative with toMap() and Integer::sum.
1. Frequency Recipes
// value -> count (Long)
Map<String, Long> freq = words.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// value -> count (Integer), with toMap
Map<String, Integer> freq2 = words.stream()
.collect(Collectors.toMap(w -> w, w -> 1, Integer::sum));
// characters of a String
Map<Character, Long> chars = text.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
2. How Frequency Counting Works
groupingBy(Function.identity(), counting()) uses each element as its own key and counts the elements per key. The result is a HashMap<T, Long>; pass TreeMap::new or LinkedHashMap::new as a map factory for sorted or first-seen order.
The toMap(k, x -> 1, Integer::sum) variant maps every element to 1 and adds the ones for repeated keys. It yields Integer counts and is equally efficient. Either way, the work is a single pass over the data.
counting() stores how often it occurred.3. Real-World Examples
Example 1: Word frequency in text
Count how often each word appears in customer feedback, ignoring case and punctuation, and list the most common first.
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FeedbackWords {
public static void main(String[] args) {
String feedback = "Fast delivery. Great packaging! Delivery was fast, very fast; packaging could be greener.";
Map<String, Long> freq = Arrays.stream(feedback.toLowerCase().split("[^a-z]+"))
.filter(w -> w.length() > 3)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
freq.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.limit(4)
.forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
}
}
fast 3 delivery 2 packaging 2 could 1
How it works: Splitting on non-letters removes punctuation, the filter drops short words, and sorting the entries by count (ties by word) gives a top-four list.
Example 2: Character frequency
Count the letters in a product code, preserving the order of first appearance.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharFrequency {
public static void main(String[] args) {
String code = "BANANA-BREAD";
Map<Character, Long> freq = code.chars()
.filter(Character::isLetter)
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
System.out.println(freq);
}
}
{B=2, A=4, N=2, R=1, E=1, D=1}
How it works: chars() gives character codes; mapToObj(c -> (char) c) boxes them as Character keys. A LinkedHashMap keeps the order in which letters first appear.
Example 3: Frequency of an object property (Java 16+)
Count orders per payment method and show the most used method.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class PaymentMethodUsage {
record Order(String id, String paymentMethod) { }
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("1", "UPI"), new Order("2", "Card"), new Order("3", "UPI"),
new Order("4", "COD"), new Order("5", "UPI"), new Order("6", "Card"));
Map<String, Integer> usage = orders.stream()
.collect(Collectors.toMap(Order::paymentMethod, o -> 1, Integer::sum, TreeMap::new));
String mostUsed = usage.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse("none");
System.out.println(usage);
System.out.println("Most used: " + mostUsed);
}
}
{COD=1, Card=2, UPI=3}
Most used: UPI
How it works: The toMap() variant counts with Integer values: each order contributes 1 and Integer::sum adds them up per method.
Example 4: Values that occur exactly once (Java 9+)
Find the first product code in a list that occurs only once.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FirstUnique {
public static void main(String[] args) {
List<String> scans = List.of("P7", "P3", "P7", "P9", "P3", "P5");
String firstUnique = scans.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse("none");
System.out.println("First unique scan: " + firstUnique);
}
}
First unique scan: P9
How it works: A frequency map in first-seen order answers many questions: the first unique value, all unique values, or all repeated values.
4. Real-World Use Cases
- Text analytics: word clouds, keyword extraction, search term reports.
- Business metrics: orders per payment method, tickets per category.
- Validation: character counts in codes and passwords.
- Interview problems: first non-repeating character, most frequent element.
5. Important Points
counting()returnsLong;toMap(..., Integer::sum)returnsInteger.- Order: the default map has none; use a
TreeMaporLinkedHashMap. - Normalise case and punctuation before counting text.
- Characters:
chars()counts UTF-16 units; usecodePoints()for emoji. - Ties: when picking the most frequent value, add a tie-breaker for a predictable answer.
6. Frequency Approaches Compared
| Approach | Count type | Notes |
|---|---|---|
groupingBy(identity(), counting()) | Long | Most common; composes with other collectors |
toMap(k, x -> 1, Integer::sum) | Integer | Also one pass |
Map.merge() in a loop | Any | Classic imperative approach |
Collections.frequency() per value | int | Quadratic; avoid for large data |
For only the repeated values, see Find Duplicate Elements; for sorting the result, see Map Sorting Using Streams.
7. Common Mistakes and Best Practices
Collecting into Map<String, Integer> with counting()
Map<String, Integer> freq = words.stream().collect(groupingBy(w -> w, counting())); // does not compile: values are Long
Declare Map<String, Long>, or use summingInt(w -> 1) or the toMap() variant.
Counting without normalising
"Fast", "fast" and "fast," are three different keys unless you lower-case and strip punctuation first, as Example 1 does.
Other mistakes to avoid
- Printing a
HashMapand expecting sorted output. - Using
Collections.frequency()inside a stream over the same list. - Ignoring ties when reporting the most frequent value.
8. Summary
groupingBy(identity(), counting())builds a value-to-count map in one pass.toMap(k, x -> 1, Integer::sum)givesIntegercounts.- Normalise text and choose a map type for the order you need.
- Stream the map's entries to find the most frequent or unique values.
9. References
Frequently Asked Questions (FAQ)
Q1. How do I count the frequency of elements in a list with Java streams?
Use list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())). The result maps each distinct element to its count as a Long.
Q2. How do I count character frequency in a String?
Use text.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).
Q3. How do I get the most frequent element?
Build the frequency map, then stream its entries and call max(Map.Entry.comparingByValue()), adding a key comparator to break ties if needed.
Q4. How can I get Integer counts instead of Long?
Use Collectors.toMap(x -> x, x -> 1, Integer::sum) or groupingBy(x -> x, Collectors.summingInt(x -> 1)).
Q5. How do I keep the frequency map in first-seen order?
Pass LinkedHashMap::new as the map factory: groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()).