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
LinkedHashMaphere.
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
remappingFunctionfunction is only called if the mapping for thekeyis present. -
The
remappingFunctionis aBiFunctionthat takes two arguments as input and returns a value. -
The value returned from the
remappingFunctionwill be updated for the passedkey. -
If
nullis returned from theremappingFunction, then the entry will be removed.
Return value
-
If
keyis present, the new updated value for thekeyis returned. -
If the
keyis not present, thennullis 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.