Related Tags

java

# What is the HashMap compute() method in Java?

Talha Ashar

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);

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 $18$ proceeds to compute a new value, i.e., $30$, 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 $21$ computes a new value, i.e., $15$, 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.

RELATED TAGS

java

CONTRIBUTOR

Talha Ashar