How does the Collectors.toUnmodifiableMap() method handle duplicate keys in Java 10?

Java MCQ: How does the Collectors.toUnmodifiableMap() method handle duplicate keys in Java 10?

a) It merges the values associated with duplicate keys
b) It throws an IllegalStateException
c) It ignores duplicate keys
d) It keeps only the first occurrence of the key

Answer:

b) It throws an IllegalStateException

Explanation:

The Collectors.toUnmodifiableMap() method, introduced in Java 10, throws an IllegalStateException if it encounters duplicate keys while collecting elements into an unmodifiable map. This method is part of the java.util.stream.Collectors class and is used to collect key-value pairs from a stream into a map that cannot be modified after it is created.

Here’s an example that demonstrates this behavior:

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ToUnmodifiableMapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = Stream.of("John", "Jane", "John")
                                             .collect(Collectors.toUnmodifiableMap(
                                                 name -> name,
                                                 name -> name.length()));

        // This will throw IllegalStateException because of duplicate keys
        System.out.println(map);
    }
}

In this example, the call to Collectors.toUnmodifiableMap() will throw an IllegalStateException because the key “John” appears more than once. This behavior ensures that the resulting map has unique keys, as required by the map contract.

The Collectors.toUnmodifiableMap() method is useful when you need a read-only map that is guaranteed to have unique keys and remain unchanged, ensuring data integrity and preventing accidental modifications.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top