What is the LinkedHashMap.compute method in Java?
LinkedHashMap
A LinkedHashMap is same as HashMap, except the LinkedHashMap maintains the insertion order, whereas the HashMap does not.
Internally, the LinkedHashMap uses the doubly-linked list to maintain the insertion order.
Read more about
LinkedHashMaphere.
What is the compute method in LinkedHashMap?
The LinkedHashMap.compute() method in Java computes a new value for the specified key using a mapping function provided by the user.
Syntax
public V compute(K key, BiFunction remappingFunction)
Parameters
-
key: The key for which the new value is computed. -
remappingFunction: ABiFunctionthat takes two arguments as input and returns a single value. The value returned from theBiFunctionwill be used to update the value of the passed key of the map. If we returnnullfrom theBiFunction, then the mapping for the key will be removed.
Return
The compute method will return the new value associated with the key.
Code
The below code demonstrates how to use the compute method.
import java.util.LinkedHashMap;class Compute {public static void main( String args[] ) {LinkedHashMap<String, Integer> map = new LinkedHashMap<>();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 above code, we create a
LinkedHashMapwith the namemapand add some entries to it. -
First, we call the
computemethod on themapfor theMathskey.
Integer newVal = map.compute("Maths", (key, oldVal) -> { return oldVal + 10; });
-
The above code will compute a new value inside the
BiFunctionand update the value associated with theMathskey. -
Then, we call the
computemethod on themapfor theEconomicskey. There is no mapping associated with theEconomicskey, so the map remains unchanged. -
We add the
nullcheck inside theBiFunctionpassed to thecomputemethod because the BiFunction will be called with the argument:keyasEconomics.oldValasnull.
To handle the null of the oldVal, we add the null check.