Which one is better getOrDefault () or putIfAbsent () from HashMap in Java

If I need to set values ​​for a key (for many keys) in a HashMap, if it is missing, which one is better to use. getOrDefault () or putIfAbsent () Because both methods will return the value associated with the key, if it is already set. And both will take the key, the value of the pair as a parameter.

+4
source share
3 answers

Yes, they both will return the value associated with the key, if it is already installed, but it is only the recipient, and the other is the setter.

putIfAbsent

( NULL) null, else .


getOrDefault

, , defaultValue, .


, , getOrDefault. , , putIfAbsent.

,

( ) HashMap, ,

putIfAbsent.

+9

Java8 computeIfAbsent, , , , , Map .

Value v = map.computeIfAbsent(key, k -> new Value(f(k)));
+3

getOrDefault() does not mutate the map, so you will not find the value on the map if you subsequently checked its contents, for example.

HashMap<String, String> map = new HashMap<>();
map.getOrDefault("something", "default");  // returns "default"
assertTrue(map.isEmpty());

putIfAbsent() mutates the map, so you will find the values ​​on the map if you later check its contents, for example

HashMap<String, String> map = new HashMap<>();
map.putIfAbsent("something", "default");
assertFalse(map.isEmpty());

You must choose the one that suits you.

+2
source

All Articles