Java

Collectors.toMap with Merge Function

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`toMap` builds a `Map<K, V>` from a stream. The 3-arg form takes a merge function for handling duplicate keys — without it, duplicates throw IllegalStateException.
Java
Raw
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;

class Demo {
    record User(int id, String email) {}

    void example() {
        var users = List.of(
            new User(1, "alice@x.com"),
            new User(2, "bob@x.com"),
            new User(3, "alice@x.com")     // duplicate email!
        );

        // Index users by ID — unique, no collisions expected
        Map<Integer, User> byId = users.stream()
            .collect(toMap(User::id, u -> u));

        // Index by email — collision possible, must supply a merge function
        Map<String, User> byEmail = users.stream()
            .collect(toMap(
                User::email,
                u -> u,
                (existing, replacement) -> existing      // keep the first one
            ));
        System.out.println(byEmail);

        // Count occurrences by key
        Map<String, Long> emailCounts = users.stream()
            .collect(toMap(User::email, u -> 1L, Long::sum));
        // {alice@x.com=2, bob@x.com=1}
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.