What is the HashTable.computeIfAbsent method in Java?
A HashTable is a collection of key-value pairs. The object we will use as a key should implement the hashCode and equals method as well as the key, and the value should not be null.
The computeIfAbsent() method
The computeIfAbsent() method computes a new value for a specified key, but only if the key is not already present in the HashTable object.
Syntax
public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
Parameters
-
key: The key for which the new value is to be computed. -
mappingFunction: The mapping function is only called if the mapping for thekeyis not present.
The mapping function takes one argument as input and returns a value.
The value returned from the mappingFunction will be updated for the passed key. If null is returned from the mappingFunction, then no entry will be added.
Return value
-
If the
keyis not present and a new entry is added when thecomputeIfAbsent()method is called, then the new value mapped with the specified key is returned. -
If the
keyis already present, then the value associated with the specifiedkeyis returned.
Code
import java.util.Hashtable;class merge {public static void main( String args[] ) {Hashtable<String, Integer> map = new Hashtable<>();map.put("Maths", 50);map.put("Science", 60);map.put("Programming", 70);System.out.println( "The map is - " + map);System.out.println( "\nCalling computeIfAbsent method");Integer returnVal = map.computeIfAbsent("Economics", (key) ->{System.out.println( "Mapping function called");return 80;});System.out.println("The return value from the computeIfAbsent for key Economics is " + returnVal);System.out.println( "The map is\n" + map);System.out.println( "\nCalling computeIfAbsent method");returnVal = map.computeIfAbsent("Maths", (key) ->{System.out.println( "\nMapping function called");return 30;});System.out.println("The return value from the computeIfAbsent for key Maths is " + returnVal);System.out.println( "The map is\n" + map);}}
Explanation
In the above code, we create a Hashtable object with the following entries:
"Maths" - 50
"Science" - 60
"Programming" - 70
Then, we call the computeIfAbsent() method on the created map with the Economics key. The computeIfAbsent() method will check if the Economics key is not present in the map. In our case, the Economics key is not present in the map, so the mapping function will be executed, which adds a new entry to the map with the following data:
key:"Economics"value: The value returned from the mapping function.
Now, the map will be:
"Maths" - 50
"Science" - 60
"Programming" - 70
"Economics" - 80
Next, we call the computeIfAbsent() method on the created map with the Maths key. The computeIfAbsent() method will check if the Maths key is not present in the map. In our case, the Maths key is already present in the map, so the mapping function will not be executed.