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

GetOrDefult return Array which I can not change

I have below code

Map<String, List<String> myMap = new HashMap();
...
myMap
  .getOrDefault("key", new ArrayList<>())
  .add("value");

My expectation is that in case there is no value (Array) in map, it will return reference to newly created array, which I can add my "value" to.

However I see that myContext map is empty. Seems super basic, I don’t get it.

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 :

getOrDefault() – is meant for accessing the value, not for modifying the map.

If you need to modify the map, you can use instead putIfAbsent(), be aware that it return a value that was previously associated with the key (and in case the key was not present it returns null). For the snippet you’ve introduced, a more suitable option would be computeIfAbsent() which returns the current value.

Map<String, List<String>> myMap = new HashMap<>();
        
myMap.computeIfAbsent("key", k -> new ArrayList<>())
    .add("value");
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