简体   繁体   中英

map.getOrDefault().add() in Java not works

The traditional code works well like below:

Map<Integer, List<Integer>> map = new HashMap<>();
if (!map.containsKey(1)) {
   map.put(1, new ArrayList<>());
}
map.get(1).add(2);

Now I'd like to try the magic of getOrDefault:

map.getOrDefault(1, new ArrayList<>()).add(2);

But if I use the above line, then map.get(1) is null.

Why?

Because getOrDefault , as its name suggests, only gets stuff from the map. It doesn't adds a new KVP to the map. When the key is not present, the default value you pass to getOrDefault is returned, but not added to the map, so you'd be adding 2 to an array list that is thrown away immediately.

In other words, this is what your getOrDefault code is doing:

ArrayList<Integer> value;
if (!map.containsKey(1)) {
    value = new ArrayList<>();
} else {
    value = map.get(1);
}
value.add(2);

You should use computeIfAbsent instead. This method actually adds the return value from the function to the map if the key is not present:

map.computeIfAbsent(1, x -> new ArrayList<>()).add(2);

or you could do:

if(!map.contansKey(1)) map.put(1, new ArrayList<>());
map.get(1).add(2);

so you can save those lines ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM