Streams: toMap needs a merge function for duplicate keys

The two-argument Collectors.toMap throws IllegalStateException on a duplicate key. The three-argument form says how to combine the colliding values instead.

Code
var entries = List.of("a=1", "b=2", "a=3");

try {
    entries.stream().collect(Collectors.toMap(s -> s.split("=")[0], s -> s.split("=")[1]));
} catch (IllegalStateException e) {
    System.out.println("two-arg toMap failed on the duplicate key");
}

Map<String, String> merged = entries.stream().collect(Collectors.toMap(
        s -> s.split("=")[0], s -> s.split("=")[1],
        (older, newer) -> older + "+" + newer, TreeMap::new));
System.out.println("with merge function: " + merged);
Output
two-arg toMap failed on the duplicate key
with merge function: {a=1+3, b=2}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30