Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>
                toEmails = Collections
                .singletonMap("key", "Value");

        Map<String, String> userEmails = new HashMap<>();
        userEmails.put("abc@gmail.com", "abc");

        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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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("abc@gmail.com", "abc");

toEmails.putAll(userEmails);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading