Course contentsShow
← Java
Lesson 1553 of 2,87034. Collectors in DepthFree lesson

Handling Duplicate Keys in toMap()

Learn how toMap() throws IllegalStateException on duplicate keys and why this protects data integrity.

Handling Duplicate Keys in toMap()

You'll learn why toMap() throws an exception when duplicate keys appear and how this safeguards your data.

When you use Collectors.toMap() to transform a stream into a map, Java needs to ensure every key is unique—just like a dictionary can't have two identical words with different definitions. If your stream produces duplicate keys without explicit handling, toMap() immediately throws an IllegalStateException to alert you to the problem.

Why This Exception Exists

Imagine collecting people into a map using their age as the key. If two people share the same age, which person should the map store? Without clear instructions, Java refuses to guess. This exception is a safety mechanism that prevents silent data loss—it forces you to acknowledge and handle the conflict explicitly.

The Default Behavior

List<String> words = List.of("apple", "banana", "apricot");

// This THROWS IllegalStateException: "apple" and "apricot" both map to key 'a'
Map<Character, String> map = words.stream()
    .collect(Collectors.toMap(
        word -> word.charAt(0),  // key: first character
        word -> word              // value: the word itself
    ));

When the stream encounters "apricot" after already mapping 'a' → "apple", toMap() halts execution rather than overwriting or discarding data.

Data Integrity Protection

This fail-fast behavior protects you from subtle bugs. If duplicates appear unexpectedly, it's often a sign that your key-mapping function isn't appropriate for your data, or that you need to explicitly decide how to merge values.

Key Takeaway:
toMap() throws IllegalStateException when duplicate keys occur to prevent accidental data loss and force explicit conflict resolution, maintaining data integrity.