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 LinkedHashMap here.

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: 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 value of the passed key of the map. If we return null from the BiFunction, 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 LinkedHashMap with the name 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 above 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.

  • We add 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 add the null check.

Free Resources