If I have to set values for a key (for many keys) in HashMap if not present then which one is better to use. getOrDefault() or putIfAbsent() As both the method will return the value associated with the key if it is already set. And both will take key,value pair as parameter.
The Java HashMap getOrDefault() method returns the specified default value if the mapping for the specified key is not found in the hashmap. Otherwise, the method returns the value corresponding to the specified key. The syntax of the getOrDefault() method is: hashmap.get(Object key, V defaultValue)
The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance. Parameters: This method accepts two parameters: key: which is the key with which provided value has to be mapped.
putIfAbsent adds an element with the specified Value whereas computeIfAbsent adds an element with the value computed using the Key.
Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.
Yes, they will both return the value associated with the key if it is already set, but one is only a getter while the other one is a setter.
putIfAbsent
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
getOrDefault
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
If your goal is only to retrieve the value, then use getOrDefault
. Else, if you want to set the value when it does not exist, use putIfAbsent
.
According to your first sentence,
If I have to set values for a key (for many keys) in HashMap if not present then which one is better
you should use putIfAbsent
.
In Java8 There is also computeIfAbsent
which returns the value if present or if it is absent it creates it through a lambda function, adds it to the Map
and returns its value.
Value v = map.computeIfAbsent(key, k -> new Value(f(k)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With