Java Hashtable - computeIfAbsent() Method
The java.util.Hashtable.computeIfAbsent() method is used to update a value in the Hashtable, if the specified key is not already associated with a value (or is mapped to null). It tries to compute its value using the given mapping function and enters it into this map unless null. If the function returns null no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded.
Syntax
public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
key |
Specify the key with which the specified value is to be associated. |
remappingFunction |
Specify the function to compute a value. |
Return Value
Returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.
Exception
NA.
Example:
In the example below, the java.util.Hashtable.computeIfAbsent() method is used to update a value in the given Hashtable.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a Hashtable Hashtable<Integer, String> Htable = new Hashtable<Integer, String>(); //populating the Hashtable Htable.put(101, "John"); Htable.put(102, "Marry"); Htable.put(103, "Kim"); Htable.put(104, "Jo"); //printing the Hashtable System.out.println("Htable contains: " + Htable); //updating value of the specified key using computeIfAbsent method Htable.computeIfAbsent(105, k -> "Sam".concat(" Paul")); //printing the Hashtable System.out.println("Htable contains: " + Htable); } }
The output of the above code will be:
Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John} Htable contains: {105=Sam Paul, 104=Jo, 103=Kim, 102=Marry, 101=John}
❮ Java.util - Hashtable