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 key has an associated value, a new value is computed and returned.

  • If key does not have an associated value, then computeIfPresent() returns null.

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

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 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.computeIfPresent("Bananas", (key, value) -> 30);
// key not present
if(quantities.computeIfPresent("Peach", (key, value) -> 15) == null){
System.out.println("The function returned null.");
}
// new quantities
System.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 1818 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., 3030. The computeIfPresent() method also returns the newly computed value.

Similarly, the computeIfPresent() method in line 2121 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 2121 is satisfied, and an error message is output.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved