John Selawsky
Senior Java Developer and Tutor at LearningTree

How to update the value of an existing key in HashMap

Published in the Java Developer group
You know that there is always a key and a value in HashMap or any other Map. Key is called a key for a reason because you get access to values by the key. The key is unique, but the value is not. So you can’t get a key by value because values can be duplicated. In this article, we are going to find out how to update the value of an existing key in HashMap in Java. Let’s remember Java syntax. HashMap in Java is declared the next way:

 HashMap<Key, Value> name
Let's take an example. Say, we have four friends and especially for them we created and filled in a HashMap with their names.Their keys are integer numbers.

Map<Integer, String> names = new HashMap<Integer, String>();
       names.put(1, "Stan");
       names.put(2, "Kyle");
       names.put(3, "Kenny");
       names.put(4, "Cartman");
Note: you can create and fill in your Map in different ways. For example, using the initialization block. Here it is:

Map<Integer, String> names = new HashMap<Integer, String>() {
           {
               put(1, "Stan");
               put(2, "Kyle");
               put(3, "Kenny");
               put(4, "Cartman");
           }
       };
Or using of a method and a HashMap constructor with the other map argument. This method is available from version 9 and later.

Map<Integer, String> names = new HashMap<>(Map.of(1, "Stan", 2, "Kyle", 3, "Kenny", 4, "Cartman"));
As we said before, in our HashMap keys are integer numbers, and the values contain some strings, in our case, names of characters. Well, let’s say that something bad happened to Kenny (those readers who know the South Park cartoon series, know for sure that something bad has happened to Kenny pretty often). So when it happens we have to remove Kenny from this company (our HashMap), and replace him with another friend, say, by the name of Butters. This is very easy to do because it is an update value operation. Our Kenny boy has a key == 3. We need to change the value for key 3, where Kenny is located. We can use put() method to do this:

names.put(3, "Butters");
In this case, if we display our map on the screen, the result will be as follows:

{1=Stan, 2=Kyle, 3=Butters, 4=Cartman}
What if everything is fine with Kenny and we want to keep him in the company, but we have a reason to update his key? Say, he is not number three anymore, but number five. Let's just put Kenny into our map again with key 5 and print the result. We can use the put method well. Here's the complete code for this example:

import java.util.HashMap;

public class HashMapUpdKey {
   public static void main(String[] args) {
       Map<Integer, String> names = new HashMap<>(Map.of(1, "Stan", 2, "Kyle", 3, "Kenny", 4, "Cartman"));
       names.put(5, "Kenny");
       System.out.println(names);
   }
}
You've probably already guessed what the result will be:

{1=Stan, 2=Kyle, 3=Kenny, 4=Cartman, 5=Kenny}
Is this what we were expected for? Now Kenny has two keys in our HashMap. Well, strictly speaking, these are two different Kennys, whatever we mean, since our object is uniquely determined by the key. It is like a person's passport, it should be unique. So you can't just rename or update the hashmap key once added directly. This operation is simply not available. However, you can make a deceptive maneuver: insert a new entry with the new key and delete the old one. This can be done using the HashMap remove method. remove() not only removes the association but also returns the deleted value (if it was there before). Let's supplement our example with this operation:

//easy replacement example
import java.util.HashMap;

public class HashMapUpdKey {
   public static void main(String[] args) {
      Map<Integer, String> names = new HashMap<>(Map.of(1, "Stan", 2, "Kyle", 3, "Kenny", 4, "Cartman"));
           
       names.put(5, "Kenny"); //Adding “new” Kenny 
       System.out.println(names.remove(3)); //Update value of the key: Removing “old” Kenny and print out deleted value

       System.out.println(names);
   }
}
Now we finally got what we needed, updated the key by which we can find Kenny. Here is the output:
Kenny {1=Stan, 2=Kyle, 4=Cartman, 5=Kenny}
Of course, we can carry out the operations of removing the “old” Kenny and adding a new one in any order. They are essentially independent. Or shorten your code using only one line:

names.put(5, names.remove(3));
The result will be the same for sure. So, the only proper way of changing a key in Java HashMap is to delete the entry and insert the same value with a new key. You can do it in a different way but it will be almost the same story about adding and removing an element. How to update the value of an existing key in HashMap - 1
Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
John Denim Level 0, India
1 April 2022
Can refer for nested HashMap here
BigMan99 Level 15, Jacksonville, United States
11 December 2021
I love the southpark example lol just perfect