Java Hashtable - computeIfPresent() Method
The java.util.Hashtable.computeIfPresent() method is used to update a value in the Hashtable, if the specified key is present and non-null. It tries to compute a new mapping given the key and its current mapped value. If the function returns null, the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
Syntax
public V computeIfPresent( K key, BiFunction<? super K,? super V,? extends V> remappingFunction )
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 new value associated with the specified key, or null if none.
Exception
NA.
Example:
In the example below, the java.util.Hashtable.computeIfPresent() 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 computeIfPresent method Htable.computeIfPresent(103, (k, v) -> "Sam"); Htable.computeIfPresent(104, (k, v) -> "Lee"); //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: {104=Lee, 103=Sam, 102=Marry, 101=John}
❮ Java.util - Hashtable