Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 464
shyam karwa Avatar asked Apr 09 '15 13:04

shyam karwa


People also ask

What is getOrDefault in HashMap?

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)

What does the putIfAbsent method of HashMap do?

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.

What is the difference between putIfAbsent and computeIfAbsent?

putIfAbsent adds an element with the specified Value whereas computeIfAbsent adds an element with the value computed using the Key.

What is the default value in HashMap?

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.


Video Answer


2 Answers

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.

like image 80
Jean-François Savard Avatar answered Sep 23 '22 19:09

Jean-François Savard


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)));
like image 36
Mark Avatar answered Sep 21 '22 19:09

Mark