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 key does not have an associated value, then compute() returns null.

Note: If remappingFunction returns null, the key-value pair is removed from the HashMap.

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 HashMap
HashMap<String, Integer> quantities = new HashMap<>();
// populating HashMap
quantities.put("Apples", 10);
quantities.put("Bananas", 2);
quantities.put("Oranges", 5);
// original quantities
System.out.println("The original quantities are: " + quantities);
// key already present
int banana_quantity = quantities.compute("Bananas", (key, value) -> 30);
// key not present
int peach_quantity = quantities.compute("Peach", (key, value) -> 15);
// new quantities
System.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 1818 proceeds to compute a new value, i.e., 3030, 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 2121 computes a new value, i.e., 1515, 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

Copyright ©2025 Educative, Inc. All rights reserved