What is the HashMap compute() method in Java?
The compute() method of the HashMap class in Java maps a new value to a provided key.
The process is illustrated below:
To use the compute() method, you will need to import the HashMap class into the program, as shown below:
import java.util.HashMap;
The prototype of the compute() method is shown below:
public compute(K key, BiFunction remappingFunction)
Parameters
The compute() 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 compute() method computes a new value for the provided key and returns one of the following:
-
The new value associated with
key. -
If
keydoes not have an associated value, thencompute()returnsnull.
Note: If
remappingFunctionreturnsnull, the key-value pair is removed from theHashMap.
Example
The code below shows how the compute() 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.compute("Bananas", (key, value) -> 30);// key not presentint peach_quantity = quantities.compute("Peach", (key, value) -> 15);// new quantitiesSystem.out.println("The new quantities are: " + quantities);System.out.println("The new Banana quantity is: " + banana_quantity);System.out.println("The new Peach quantity is: " + peach_quantity);}}
Explanation
First, a HashMap object quantities is initialized.
Next, key-value pairs are inserted into the HashMap. All entries have unique values.
The compute() method in line proceeds to compute a new value, i.e., , for the key “Bananas”. Since “Bananas” exists in the HashMap, the compute() method updates the mapping and returns the newly computed value.
Similarly, the compute() method in line computes a new value, i.e., , for the key “Peach”. Since “Peach” does not exist in the HashMap, the compute() method creates a new mapping and returns the newly computed value.
Free Resources