The HashMap.compute()
method in Java computes a new value for the specified key.
hashmap.compute(K key, BiFunction remappingFunction)
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 used to update the passed key of the map. If we return null from the BiFunction
, then the mapping for the key will be removed.
The compute
method will return the new value associated with the key.
import java.util.HashMap;class merge {public static void main( String args[] ) {HashMap<String, Integer> map = new HashMap<>();map.put("Maths", 50);map.put("Science", 60);map.put("Programming", 70);System.out.println( "The map is - " + map);System.out.println( "\n---------------\n");System.out.println( "Calling 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);}}
In the code above, we created a HashMap
with the name map
and added some entries to it.
First, we called the compute
method on the map
for the Maths
key.
Integer newVal = map.compute("Maths", (key, oldVal) -> { return oldVal + 10; });
The code above will compute a new value inside the BiFunction
and update the value associated with the Maths
key.
Then, we called the compute
method on the map
for the Economics
key. There is no mapping associated with the Economics
key, so the map remains unchanged. We added the null
check inside the BiFunction
passed to the compute
method because the BiFunction will be called with the argument:
key
as Economics
.oldVal
as null
.To handle the null
of the oldVal
, we added the null
check.