Skip to content

Grouping & Duplicate Keys

The Course
•
20 min study

Reports often group many events under one key. Collectors can express that grouping, but the choice of result map and duplicate policy still belongs to your application. Picture the loop you would write by hand, a map from key to count updated once per event, then read the collector as a description of the same work.

Understand the contract

Collectors.groupingBy takes a key function. Its three-argument form also takes a map supplier and a downstream collector describing what happens inside each group. Here the key is the title itself, LinkedHashMap::new preserves first-seen key order, and counting() produces a Long count per group. The key lambda is a classifier, not a filter.

The nested collector is easiest to read from outside in: group titles, choose an ordered map, count each group's entries. If you only need a simple loop, keep it; fluent syntax is not a requirement for good Java. The advantage is stating a reusable combination of operations once you understand each part.

toMap answers a different question: one value per key. Its simple overload rejects duplicate keys. That is useful evidence that your supposed unique ID was not unique. The overload with a merge function lets you deliberately combine duplicates, and a map supplier makes ordering explicit. Never select “keep the last” merely to suppress an exception without deciding whether losing the earlier value is acceptable.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> titles = List.of("Read", "Test", "Read");
        Map<String, Long> counts = titles.stream().collect(
            Collectors.groupingBy(title -> title, LinkedHashMap::new, Collectors.counting())
        );
        System.out.println(counts);
    }
}
Check your prediction
Text
{Read=2, Test=1}

Trace a different case

A merge function receives the previous value and the incoming value. It must return the value to keep under that key. Integer::sum is the method reference for the static Integer.sum(a, b) method, equivalent to (previous, incoming) -> previous + incoming. It adds two counts; it does not concatenate text or choose a winner. In the following collector every event starts with value 1, and repeated events contribute again. The result is an event count, not a map of unique event records.

Compare the boundary case Java
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> counts = List.of("Read", "Test", "Read").stream().collect(
            Collectors.toMap(title -> title, title -> 1, Integer::sum, LinkedHashMap::new)
        );
        System.out.println(counts);
        System.out.println(counts.size());
    }
}
Check your prediction
Text
{Read=2, Test=1}
2

Read a nested collector from outside inward

Start with the result type: Map<String,Long> means keys are strings and each group's result is a long count. The classifier chooses the key for each input; the map supplier chooses ordering behavior; the downstream collector chooses the value stored for each group.

Write those three responsibilities separately before compressing them into one expression. For Read, Test, Read, the groups have sizes two and one. A merge policy keeping only the incoming value would lose event counts, even though the map still had the right keys.

Try equal values under different classifications and different values with the same classification. Grouping by length is not grouping by whole text. A key function is a domain decision, and a readable collector should make that decision easy to name.

Build it yourself

Exercise

Grouping & Duplicate Keys: practice

Group nonnull words by their length and count each group using a LinkedHashMap. Input Read, Go, Test, A should print {4=2, 2=1, 1=1}. Also print {} for empty input. Write a method returning Map<Integer,Long> and preserve encounter order of lengths.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Choose the property that becomes a key independently from the aggregate stored under it.

Hint 2: a first step

Use String::length as the classifier and counting as the downstream collector.

Show one solution
Java
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        System.out.println(countLengths(List.of("Read", "Go", "Test", "A")));
        System.out.println(countLengths(List.of()));
    }

    static Map<Integer, Long> countLengths(List<String> words) {
        return words.stream().collect(
            Collectors.groupingBy(String::length, LinkedHashMap::new, Collectors.counting())
        );
    }
}

Expected output:

Text
{4=2, 2=1, 1=1}
{}

The three-argument groupingBy is the key decision: the middle argument, LinkedHashMap::new, keeps lengths in first-seen order, so 4 prints before 2. The default overload returns an unspecified Map whose order you cannot promise. Collectors.counting() produces Long values, which is why the method returns Map<Integer, Long>. Empty input yields an empty map, not an error.

Change it and test again

Reverse the input order and predict the order of first-seen lengths. Compare with a loop using getOrDefault. Replace counting with collecting titles into lists as a separate experiment: the value type must change too. Test a duplicate-key toMap call without a merge function and read the rejection before choosing a policy.

Explain before moving on

What does the downstream collector do? Which part guarantees report order? Explain why groupingBy and toMap are not interchangeable merely because both return maps. A report should state whether repeated inputs represent legitimate events or conflicting identifiers.

Was this article helpful?

Your response is saved on this device.