Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

This tutorial will go through the different approaches for updating the value associated with a given key in a HashMap. First, we'll look at some common solutions using only those features that were available before Java 8. Then, we'll look at some additional solutions available in Java 8 and above.

2. Initializing Our Example HashMap

To show how to update the values in a HashMap, we have to create and populate one first. So, we'll create a map with fruits as keys and their prices as the values:

Map<String, Double> priceMap = new HashMap<>();
priceMap.put("apple", 2.45);
priceMap.put("grapes", 1.22);

We'll be using this HashMap throughout our example. Now, we're ready to get familiar with the methods for updating the value associated with a HashMap key.

3. Before Java 8

Let's start with the methods that were available before Java 8.

3.1. The put Method

The put method either updates the value or adds a new entry. If it is used with a key that already exists, then the put method will update the associated value. Otherwise, it will add a new (key, value) pair.

Let's test the behavior of this method with two quick examples:

public void givenFruitMap_whenPuttingAList_thenHashMapUpdatesAndInsertsValues() {
    Double newValue = 2.11;
    fruitMap.put("apple", newValue);
    fruitMap.put("orange", newValue);
    Assertions.assertEquals(newValue, fruitMap.get("apple"));
    Assertions.assertEquals(newValue, fruitMap.get("orange"));

The key apple is already on the map. Therefore, the first assertion will pass.

Since orange is not present in the map, the put method will add it. Hence, the other two assertions will pass as well.

3.2. The Combination of containsKey and put Methods

The combination of containsKey and put methods is another way to update the value of a key in HashMap. This option checks if the map already contains a key. In such a case, we can update the value using the put method. Otherwise, we can either add an entry to the map or do nothing.

In our case, we'll inspect this approach with a simple test:

public void givenFruitMap_whenKeyExists_thenValuesUpdated() {
    double newValue = 2.31;
    if (fruitMap.containsKey("apple")) {
        fruitMap.put("apple", newValue);
    Assertions.assertEquals(Double.valueOf(newValue), fruitMap.get("apple"));

Since apple is on the map, the containsKey method will return true. Therefore, the call to the put method will be executed, and the value will be updated.

4. Java 8 and Above

Since Java 8, many new methods are available that facilitate the process of updating the value of a key in the HashMap. So, let's get to know them.

4.1. The replace Methods

Two overloaded replace methods have been available in the Map interface since version 8. Let's look at the method signatures:

public V replace(K key, V value);
public boolean replace(K key, V oldValue, V newValue);

The first replace method only takes a key and a new value. It also returns the old value.

Let's see how the method works:

public void givenFruitMap_whenReplacingOldValue_thenNewValueSet() {
    double newPrice = 3.22;
    Double applePrice = fruitMap.get("apple");
    Double oldValue = fruitMap.replace("apple", newPrice);
    Assertions.assertEquals(oldValue, applePrice);
    Assertions.assertEquals(Double.valueOf(newPrice), fruitMap.get("apple"));

The value of the key apple will be updated to a new price with the replace method. Therefore, the second and the third assertions will pass.

However, the first assertion is interesting. What if there was no key apple in our HashMap? If we try to update the value of a non-existing key, null will be returned. Taking that into account, another question arises: What if there was a key with a null value? We cannot know whether that value returned from the replace method was indeed the value of the provided key or if we've tried to update the value of a non-existing key.

So, to avoid misunderstanding, we can use the second replace method. It takes three arguments:

  • a key
  • the current value associated with the key
  • the new value to associate with the key

It will update the value of a key to a new value on one condition: If the second argument is the current value, the key value will be updated to a new value. The method returns true for a successful update. Otherwise, false is returned.

So, let's implement some tests to check the second replace method:

public void givenFruitMap_whenReplacingWithRealOldValue_thenNewValueSet() {
    double newPrice = 3.22;
    Double applePrice = fruitMap.get("apple");
    boolean isUpdated = fruitMap.replace("apple", applePrice, newPrice);

public void givenFruitMap_whenReplacingWithWrongOldValue_thenNewValueNotSet() {
    double newPrice = 3.22;
    boolean isUpdated = fruitMap.replace("apple", Double.valueOf(0), newPrice);

Since the first test calls the replace method with the current value of the key, that value will be replaced.

On the other hand, the second test is not invoked with the current value. Thus, false is returned.

4.2. The Combination of getOrDefault and put Methods

The getOrDefault method is a perfect choice if we don't have an entry for the provided key. In that case, we set the default value for a non-existing key. Then, the entry is added to the map. With this approach, we can easily escape the NullPointerException.

Let's try this combination with a key that is not originally on the map:

public void givenFruitMap_whenGetOrDefaultUsedWithPut_thenNewEntriesAdded() {
    fruitMap.put("plum", fruitMap.getOrDefault("plum", 2.41));
    Assertions.assertEquals(Double.valueOf(2.41), fruitMap.get("plum"));

Since there is no such key, the getOrDefault method will return the default value. Then, the put method will add a new (key, value) pair. Therefore, all assertions will pass.

4.3. The putIfAbsent Method

The putIfAbsent method does the same as the previous combination of the getOrDefault and put methods.

If there is no pair in the HashMap with the provided key, the putIfAbsent method will add the pair. However, if there is such a pair, the putIfAbsent method won't change the map.

But, there is an exception: If the existing pair has a null value, then the pair will be updated to a new value.

Let's implement the test for the putIfAbsent method. We'll test the behavior with two examples:

public void givenFruitMap_whenPutIfAbsentUsed_thenNewEntriesAdded() {
    double newValue = 1.78;
    fruitMap.putIfAbsent("apple", newValue);
    fruitMap.putIfAbsent("pear", newValue);
    Assertions.assertNotEquals(Double.valueOf(newValue), fruitMap.get("apple"));
    Assertions.assertEquals(Double.valueOf(newValue), fruitMap.get("pear"));

A key apple is present on the map. The putIfAbsent method won't change its current value.

At the same time, the key pear is missing from the map. Hence, it will be added.

4.4. The compute Method

The compute method updates the value of a key based on the BiFunction provided as the second parameter. If the key doesn't exist on the map, we can expect a NullPointerException.

Let's check this method's behavior with a simple test:

public void givenFruitMap_whenComputeUsed_thenValueUpdated() {
    double oldPrice = fruitMap.get("apple");
    BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
    fruitMap.compute("apple", (k, v) -> powFunction.apply(v, 2));
      Double.valueOf(Math.pow(oldPrice, 2)), fruitMap.get("apple"));
      NullPointerException.class, () -> fruitMap.compute("blueberry", (k, v) -> powFunction.apply(v, 2)));

As expected, since the key apple exists, its value in the map will be updated. On the other hand, there is no key blueberry, so the second call to the compute method in the last assertion will result in a NullPointerException.

4.5. The computeIfAbsent Method

The previous method throws an exception if there's no pair in the HashMap for a specific key. The computeIfAbsent method will update the map by adding a (key, value) pair if it doesn't exist.

Let's test the behavior of this method:

public void givenFruitMap_whenComputeIfAbsentUsed_thenNewEntriesAdded() {
    fruitMap.computeIfAbsent("lemon", k -> Double.valueOf(k.length()));
    Assertions.assertEquals(Double.valueOf("lemon".length()), fruitMap.get("lemon"));

The key lemon doesn't exist on the map. Hence, the computeIfAbsent method adds an entry.

4.6. The computeIfPresent Method

The computeIfPresent method updates the value of a key if it is present in the HashMap.

Let's see how we can use this method:

public void givenFruitMap_whenComputeIfPresentUsed_thenValuesUpdated() {
    Double oldAppleValue = fruitMap.get("apple");
    BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
    fruitMap.computeIfPresent("apple", (k, v) -> powFunction.apply(v, 2));
    Assertions.assertEquals(Double.valueOf(Math.pow(oldAppleValue, 2)), fruitMap.get("apple"));

The assertion will pass since the key apple is in the map, and the computeIfPresent method will update the value according to the BiFunction.

4.7. The merge Method

The merge method updates the value of a key in the HashMap using the BiFunction if there is such a key. Otherwise, it will add a new (key, value) pair, with the value set to the value provided as the second argument to the method.

So, let's inspect the behavior of this method:

public void givenFruitMap_whenMergeUsed_thenNewEntriesAdded() {
    double defaultValue = 1.25;
    BiFunction<Double, Integer, Double> powFunction = (x1, x2) -> Math.pow(x1, x2);
    fruitMap.merge("apple", defaultValue, (k, v) -> powFunction.apply(v, 2));
    fruitMap.merge("strawberry", defaultValue, (k, v) -> powFunction.apply(v, 2));
    Assertions.assertEquals(Double.valueOf(defaultValue), fruitMap.get("strawberry"));
    Assertions.assertEquals(Double.valueOf(Math.pow(defaultValue, 2)), fruitMap.get("apple"));

The test first executes the merge method on the key apple. It's already on the map, so its value will change. It will be a square of the defaultValue parameter that we passed to the method.

The key strawberry is not present on the map. Therefore, the merge method will add it with defaultValue as the value.

5. Conclusion

In this article, we described several ways to update the value associated with a key in a HashMap.

First, we started with the most common approaches. Then, we showed several methods that have been available since Java 8.

As always, the code for these examples is available over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Inline Feedbacks
View all comments