1. Overview

In Java, the HashMap is a widely used data structure that stores elements in key-value pairs, providing fast access and retrieval of data. Sometimes, when working with HashMaps, we may want to modify the key of an existing entry.

In this tutorial, we’ll explore how to modify a key in a HashMap in Java.

2. Using remove() Then put()

First, let’s look at how HashMap stores key-value pairs. HashMap uses the Node type to maintain key-value pairs internally:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
   ...
  }

As we can see, the key declaration has the final keyword. Therefore, we cannot reassign a key object after we put it into a HashMap.

Although we cannot simply replace a key, we can still achieve our expected result in other ways. Next, Let’s look at our problem from a different angle.

Let’s say we have an entry K1 -> V in a HashMap. Now, we want to change K1 into K2 to have K2 -> V. Indeed, the most straightforward idea to achieve that is finding the entry by “K1” and replacing the key “K1” with “K2”. However, we can also remove the K1 -> V association and add a new K2 -> V entry.

The Map interface offers the remove(key) method to remove an entry from the map by its key. Further, the remove() method returns the value removed from the map.

Next, let’s see how this approach works through an example. For simplicity, we’ll use unit test assertions to verify if the result is as we expect:

Map<String, Integer> playerMap = new HashMap<>();

playerMap.put("Kai", 42);
playerMap.put("Amanda", 88);
playerMap.put("Tom", 200);

The simple code above shows a HashMap, which holds a few associations of player names (String) and their scores (Integer). Next, let’s replace the player name “Kai” in the entry “Kai” -> 42 with “Eric“:

// replace Kai with Eric
playerMap.put("Eric", playerMap.remove("Kai"));

assertFalse(playerMap.containsKey("Kai"));
assertTrue(playerMap.containsKey("Eric"));
assertEquals(42, playerMap.get("Eric"));

As we can see, the single-line statement playerMap.put(“Eric”, playerMap.remove(“Kai”)); does two things. It removes the entry with the key “Kai“, takes its value (42), and adds a new entry “Eric” -> 42.

When we run the test, it passes. So, this approach works as expected.

Although our problem is solved, there is a potential question. We know that the HashMap‘s key is a final variable. So, we cannot reassign the variable. But we can modify a final object’s value. Well, in our playerMap example, the key is String. We cannot change its value as Strings are immutable. But can we solve the problem by modifying the key if it’s a mutable object?

Next, let’s figure it out.

3. Never Modify Keys in a HashMap

First, we shouldn’t use a mutable object as the key in a HashMap in Java, which can lead to potential issues and unexpected behavior.

This is because the key object in a HashMap is used to compute a hash code that determines the bucket where the corresponding value will be stored. If the key is mutable and changed after being used as a key in the HashMap, the hash code can also change. As a result, we won’t retrieve the value associated with the key correctly since it will be located in the wrong bucket.

Next, let’s understand it through an example.

First, we create a Player class with only one single property:

class Player {
    private String name;
    public Player(String name) {
        this.name = name;
    }
    
    // getter and setter methods are omitted
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Player)) {
            return false;
        }
        Player player = (Player) o;
        return name.equals(player.name);
    }
    
    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

As we can see, the Player class has a setter on the name property. So, it’s mutable. Further, the hashCode() method calculates the hash code using the name property. This means changing the name of a Player object can make it have a different hash code.

Next, let’s create a map and put some entries in it, using Player objects as keys:

Map<Player, Integer> myMap = new HashMap<>();
Player kai = new Player("Kai");
Player tom = new Player("Tom");
Player amanda = new Player("Amanda");
myMap.put(kai, 42);
myMap.put(amanda, 88);
myMap.put(tom, 200);
assertTrue(myMap.containsKey(kai));

Next, let’s change the player kai‘s name from “Kai” to “Eric”, then verify if we can get the expected result:

//change Kai's name to Eric
kai.setName("Eric");
assertEquals("Eric", kai.getName());
Player eric = new Player("Eric");
assertEquals(eric, kai);

// now, the map contains neither Kai nor Eric:
assertFalse(myMap.containsKey(kai));
assertFalse(myMap.containsKey(eric));

As the test above shows, *after changing kai‘s name to “Eric“, we cannot retrieve the entry “Eric” -> 42 anymore using kai or eric.* However, the object Player(“Eric”) exists in the map as a key:

// although the Player("Eric") exists:
long ericCount = myMap.keySet()
  .stream()
  .filter(player -> player.getName()
    .equals("Eric"))
  .count();
assertEquals(1, ericCount);

To understand why this happened, we first need to understand how HashMap works.

HashMap maintains an internal hashtable to store the hash codes of the keys when they are added to the map. A hash code references a map entry. As we retrieve an entry, for example, by using the get(key) method, HashMap computes the hash code of the given key object and looks up the hash code in the hashtable.

In the example above, we put kai(“Kai”) in the map. So, the hash code is computed based on the string “Kai”. HashMap stored the result, let’s say “hash-kai”,  in the hashtable. Later, we changed the kai(“Kai”) to kai(“Eric”). When we tried to retrieve the entry by kai(“Eric”), HashMap computed “hash-eric” as the hash code. Then, it looked it up in the hashtable. Of course, it won’t find it.

It isn’t hard to imagine that if we did this in a real application, the root cause of this unexpected behavior can be hard to find.

Therefore, we shouldn’t use mutable objects as keys in a HashMap. Further, we should never modify the keys.

4. Conclusion

In this article, we’ve learned the “remove() then put()” approach to replacing a key in a HashMap. Further, we discussed through an example why we should avoid using mutable objects as keys in a HashMap and why we should never modify keys in a HashMap.

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