00:00

Count Element Frequency Using Java Streams

Last updated:

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

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 word frequency The words tea, coffee, tea, juice, tea and coffee are grouped by themselves and counted, producing tea 3, coffee 2 and juice 1. WORDS tea coffee tea juice tea coffee groupingBy(identity(), counting()) MAP tea=3 coffee=2 juice=1
Figure 1: Each distinct value becomes a key, and 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.

FeedbackWords.java
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()));
    }
}
Output
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.

CharFrequency.java
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);
    }
}
Output
{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.

PaymentMethodUsage.java
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);
    }
}
Output
{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.

FirstUnique.java
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);
    }
}
Output
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() returns Long; toMap(..., Integer::sum) returns Integer.
  • Order: the default map has none; use a TreeMap or LinkedHashMap.
  • Normalise case and punctuation before counting text.
  • Characters: chars() counts UTF-16 units; use codePoints() for emoji.
  • Ties: when picking the most frequent value, add a tie-breaker for a predictable answer.

6. Frequency Approaches Compared

ApproachCount typeNotes
groupingBy(identity(), counting())LongMost common; composes with other collectors
toMap(k, x -> 1, Integer::sum)IntegerAlso one pass
Map.merge() in a loopAnyClassic imperative approach
Collections.frequency() per valueintQuadratic; 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()

Wrong
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 HashMap and 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) gives Integer counts.
  • 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