HashTable compute() method in Java with Examples
Last Updated :
02 Jun, 2023
The compute(Key, BiFunction) method of Hashtable class allows to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found).
- If the remapping function passed in compute() of Hashtable returns null as a return value then the mapping is removed from Hashtable(or remains absent if initially absent).
- If the remapping function throws an exception, the exception is rethrown, and the current mapping is left unchanged.
- During computation, modification this map using this method is not allowed.
- The compute() method can be used to update an existing value inside Hashtable. For example, This mapping append string value of mapping:
Hashtable.compute(key, (k, v) -> v.append("strValue"))
- This method will throw a ConcurrentModificationException if the remapping function modified this map during computation.
Syntax:
public V
compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
Parameters: This method accepts two parameters:
- key: key with which the value is to be associated.
- remappingFunction: function to do the operation on value.
Returns: This method returns new value associated with the specified key, or null if none.
Exception: This method throws:
- ConcurrentModificationException: if it is detected that the remapping function modified this map.
Below programs illustrate the compute(Key, BiFunction) method:
Program 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Map<String, Integer> table = new Hashtable<>();
table.put("Pen", 10 );
table.put("Book", 500 );
table.put("Clothes", 400 );
table.put("Mobile", 5000 );
System.out.println("hashTable: " + table.toString());
table.compute("Pen", (key, val)
-> val + 15 );
table.compute("Clothes", (key, val)
-> val - 120 );
System.out.println(" new hashTable: " + table);
}
}
|
Output:
hashTable: {Book=500, Mobile=5000, Pen=10, Clothes=400}
new hashTable: {Book=500, Mobile=5000, Pen=25, Clothes=280}
Program 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Map<Integer, String> table = new Hashtable<>();
table.put( 1 , "100RS");
table.put( 2 , "500RS");
table.put( 3 , "1000RS");
System.out.println("hashTable: "
+ table.toString());
table.compute( 3 , (key, val)
-> val.substring( 0 , 4 ) + "00RS");
table.compute( 2 , (key, val)
-> val.substring( 0 , 2 ) + "$");
System.out.println(" new hashTable: " + table);
}
}
|
Output:
hashTable: {3=1000RS, 2=500RS, 1=100RS}
new hashTable: {3=100000RS, 2=50$, 1=100RS}
References: https://docs.oracle.com/javase/10/docs/api/java/util/Hashtable.html#compute(K, java.util.function.BiFunction)
Share your thoughts in the comments
Please Login to comment...