What is the LinkedHashMap.computeIfPresent method in Java?

Overview

A LinkedHashMap is the same as HashMap, except that LinkedHashMap maintains the insertion order, while 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 computeIfPresent method in LinkedHashMap?

The LinkedHashMap.computeIfPresent() method computes a new value for the specified key only if the key is already present in the map.

Syntax


public V computeIfPresent(K key, BiFunction remappingFunction)

Arguments

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

remappingFunction

  • The remappingFunction function is only called if the mapping for the key is present.

  • The remappingFunction is a BiFunction that takes two arguments as input and returns a value.

  • The value returned from the remappingFunction will be updated for the passed key.

  • If null is returned from the remappingFunction, then the entry will be removed.

Return value

  • If key is present, the new updated value for the key is returned.

  • If the key is not present, then null is returned.

Code

import java.util.LinkedHashMap;
class ComputeIfPresent {
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);
Integer returnVal = map.computeIfPresent("Maths", (key, oldVal) ->{
System.out.println( "\nReMapping function called with key " + key + " value " + oldVal );
return 80;
});
System.out.println("\nAfter calling computeIfPresent for key Maths");
System.out.println("\nThe return value is " + returnVal);
System.out.println( "The map is\n" + map);
returnVal = map.computeIfPresent("Economics", (key, oldVal) ->{
System.out.println( "\n ReMapping function called");
return 80;
});
System.out.println("\nAfter calling computeIfPresent for key Economics");
System.out.print("The return value is ");
System.out.println(returnVal);
System.out.println( "The map is\n" + map);
}
}

Explanation

In the above code, we created a LinkedHashMap with the entries given below.


"Maths" - 50
"Science" - 60
"Programming" - 70

The program then calls the computeIfPresent method on the created map with the Maths key. computeIfPresent will check if the key Maths is present in the map or not. Since the Maths key is already present in the map, the mapping function will be executed.

Now, the map will be as follows:


"Maths" - 80
"Science" - 60
"Programming" - 70

Finally, the program calls the computeIfPresent method on the created map with the Economics key.

computeIfPresent will check if the key Economics is present in the map.

In our case, the Economics key is not present in the map, so the mapping function will not be executed and null is returned.

Free Resources