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.
>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");