Search code examples
javahashmap

Hashmap is unable to be added to a collecitons.singletonmap


import java.util.*;

public class Hash_Map_Demo {
    public static void main(String[] args) {
        Map<String, String> userEmails = new HashMap<>();
        userEmails.put("[email protected]", "abc");

        Map<String, String> toEmails = Collections.singletonMap("key", "Value");
        toEmails.putAll(userEmails);
    }
}

When I'm trying to run the above code, I'm encountering the following exception:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:209)
    at java.util.AbstractMap.putAll(AbstractMap.java:281)
    at Hash_Map_Demo.main(Hash_Map_Demo.java:13)

I understand that here I'm trying to add a Hashmap to Collections.singletonmap. But aren't they same and what is happening behind.


Solution

  • Collections.singletonMap() returns an immutable map. Use some other Map implementation, for example:

    HashMap<String, String> toEmails = new HashMap();
    toEmails.put("key", "Value")
    
    Map<String, String> userEmails = new HashMap<>();
    userEmails.put("[email protected]", "abc");
    
    toEmails.putAll(userEmails);