What is the HashMap computeIfPresent() method in Java?
The computeIfPresent() method of the HashMap class in Java maps a new value to a provided key, given that the key is present in the HashMap.
The process is illustrated below:
To use the computeIfPresent() method, you will need to import the HashMap class into the program, as shown below:
import java.util.HashMap;
The prototype of the computeIfPresent() method is shown below:
public computeIfPresent(K key, BiFunction remappingFunction)
Parameters
The computeIfPresent() method takes the following parameters:
key: The key for which the value must be computed.remappingFunction: The function that computes the new value.
Return value
The computeIfPresent() method checks the value associated with the provided key parameter and returns one of the following:
-
If
keyhas an associated value, a new value is computed and returned. -
If
keydoes not have an associated value, thencomputeIfPresent()returnsnull.
Note: If the
remappingFunctionreturnsnull, the key-value pair is removed from theHashMap.
Example
The code below shows how the computeIfPresent() method works in Java:
import java.util.HashMap;class Main {public static void main(String[] args){// initializing HashMapHashMap<String, Integer> quantities = new HashMap<>();// populating HashMapquantities.put("Apples", 10);quantities.put("Bananas", 2);quantities.put("Oranges", 5);// original quantitiesSystem.out.println("The original quantities are: " + quantities);// key already presentint banana_quantity = quantities.computeIfPresent("Bananas", (key, value) -> 30);// key not presentif(quantities.computeIfPresent("Peach", (key, value) -> 15) == null){System.out.println("The function returned null.");}// new quantitiesSystem.out.println("The new quantities are: " + quantities);}}
Explanation
First, a HashMap object quantities is initialized.
Next, key-value pairs are inserted into the HashMap. All entries have unique values.
The computeIfPresent() method in line proceeds to iterate over each mapping in the HashMap to find the value associated with the key “Bananas”. Since “Bananas” exists in the HashMap, the computeIfPresent() method computes a new value for the specified key, i.e., . The computeIfPresent() method also returns the newly computed value.
Similarly, the computeIfPresent() method in line proceeds to iterate over each mapping in the HashMap to find the value associated with the key “Peach”. Since “Peach” does not exist in the HashMap, the computeIfPresent() method returns null. As a result, the if-condition in line is satisfied, and an error message is output.
Free Resources