How to use the Hashtable.compute method in Java

A hash table is a collection of key-value pairs. The object to be used as a key should implement the hashCode and equals methods, and the key and the value should not be null. You can read about the difference between HashTable and HashMap here.

The compute() method computes a new value for the specified key using a mapping function provided as an argument. If the specified key is not present, then no operation is performed and null is returned.

Syntax

public V compute(K key, BiFunction remappingFunction)

Parameters

  • key: The key for which the new value is to be computed.

  • remappingFunction:

    • A BiFunction that takes two arguments as input and returns a single value.
    • The value returned from the BiFunction will be updated as the value of the passed key of the map.
    • If we return null from the BiFunction, then the mapping for the key will be removed.
    • If the function itself throws an exception, then the exception is rethrown, and the current mapping is left unchanged.

Return

  • The compute() method will return the new value associated with the key.

Code

The code below demonstrates how to use the compute() method.

import java.util.Hashtable;
class Compute {
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 compute function for key Maths");
Integer newVal = map.compute("Maths", (key, oldVal) -> { return oldVal + 10; });
System.out.println("\nThe return value is " + newVal);
System.out.println( "The map is - " + map);
System.out.println( "\n---------------\n");
System.out.println( "Calling compute function for key Economics\n");
newVal =
map.compute("Economics",
(key, oldVal) -> {
System.out.print("Inside BiFunction: The key is ");
System.out.print(key);
System.out.print(". The value is ");
System.out.println(oldVal + ".");
if(oldVal != null) {
return oldVal + 10;
}
return null;
});
System.out.println("\nThe return value is " + newVal);
System.out.println( "The map is - " + map);
}
}

Explanation

  • In the code above, we create a Hashtable named map and add some entries to it.

  • First, we call the compute() method on the map for the Maths key.

Integer newVal = map.compute("Maths", (key, oldVal) -> { return oldVal + 10; });
  • The code will compute a new value inside the BiFunction and update the value associated with the Maths key.

  • Then, we call the compute() method on the map for the Economics key. There is no mapping associated with the Economics key, so the map remains unchanged and returns null.

Free Resources