Java Hashtable - compute() Method
The java.util.Hashtable.compute() method is used to update a value in the Hashtable. It tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). If the function returns null, the mapping is removed (or remains absent if initially absent). If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
Syntax
public V compute(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.compute() 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 compute method Htable.compute(101, (k, v) -> v.concat(" Paul")); Htable.compute(104, (k, v) -> "Sam"); //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=Sam, 103=Kim, 102=Marry, 101=John Paul}
❮ Java.util - Hashtable