Collectors ToMap Merge Conflicts

Duplicate keys make Collectors.toMap throw IllegalStateException unless a merge function is supplied; a LinkedHashMap factory keeps encounter order.

JavaData Integrity

Code

snippet
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TagCounter {

    public static void main(String[] args) {
        record Item(String label, int weight) {}
        List<Item> items = List.of(
                new Item("cache", 2),
                new Item("api", 1),
                new Item("cache", 4));

        // No merge function: a duplicate key throws IllegalStateException outright
        try {
            items.stream().collect(Collectors.toMap(Item::label, Item::weight));
        } catch (IllegalStateException e) {
            System.out.println("no merge fn -> " + e.getMessage());
        }

        // Merge function: duplicates combine by policy - here weights are summed
        Map<String, Integer> totals = items.stream()
                .collect(Collectors.toMap(Item::label, Item::weight, Integer::sum));
        System.out.println("merged totals: " + totals);

        // Pass a map factory: LinkedHashMap keeps first-appearance key order
        Map<String, Integer> ordered = items.stream()
                .collect(Collectors.toMap(
                        Item::label, Item::weight, Integer::sum, LinkedHashMap::new));
        System.out.println("ordered keys: " + ordered.keySet());
    }
}

How the snippet works

Collectors ToMap Merge Conflicts is built around the classes TagCounter and Item and the function main.

Data flows through a stream pipeline where each stage returns a new view rather than mutating.

Applying it

The demo output is labeled (no merge fn ->, merged totals:, ordered keys:), so every printed line maps back to its originating operation.

Statements that matter

items.stream().collect(Collectors.toMap(Item::label, Item::weight));
.collect(Collectors.toMap(Item::label, Item::weight, Integer::sum));
.collect(Collectors.toMap(
        Item::label, Item::weight, Integer::sum, LinkedHashMap::new));

Interactive Tools for This Topic

FAQ

What does Collectors ToMap Merge Conflicts print when run?
Execute the whole file; each printed line is prefixed with a label like `no merge fn ->`, `merged totals:`, `ordered keys:`.