Java : How to update the value of an existing key in HashMap | put() vs replace()

In this article we will discuss different ways to update the value of an existing key in HashMap in Java.

Suppose we have a HashMap of words and their frequency count i.e.

// Create a Map of words and their frequency count
HashMap<String, Integer> mapOfWords = new HashMap<String, Integer>() {
	{
		put("John", 25);
		put("at", 2);
		put("from", 10);
		put("is", 5);
	}
};

Now we want to update the value of an existing key “from” to 67. Let’s see how do that,

Updating the value of an existing key using put()

public V put(K key, V value)

It will update the value V for key K and returns the old value i.e.

// Update the value of key "from" to 67, it will return the old value.
Integer oldValue = mapOfWords.put("from", 67);

But what if we try to update the value of key that don’t even exist in HashMap using put() i.e.

// Now try to update a value in HashMap for key that don't even exists in
// HashMap using put()
oldValue = mapOfWords.put("frm", 99);

// oldValue returned by put() should be null.
assert (oldValue == null);

It will return null and will add a new entry in the map for given key and value. So, map’s content will be now,

{frm=99, at=2, John=25, from=67, is=5}

But when put() returns null, we can not be sure that that it has added a new entry in the map or there was an existing key in the map whose value was null.

To improve over this HashMap provides two overloaded versions of replace() member function.

Updating the value of an existing key using replace()

First overloaded version of replace,

public V replace(K key, V value)

It will  avoid unnecessary addition to hashmap while updating value  of non existing key in hashmap i.e.

// Update the value of key "from" to 56, it will return the old value.
oldValue = mapOfWords.replace("from", 56);

Now try to update a value in HashMap for key that don’t even exists in  HashMap using replace()

oldValue = mapOfWords.replace("frmee", 99);

It will NOT add the new key value entry in map and returns null.

// oldValue returned by replace() should be null, because key dosn't exists in Map
assert (oldValue == null);

But if replace() returns null, we can not be always sure that that there was no  entry in map with given key and it has not updating anything in map. There can be an existing key in the map whose value was null and now updated to new value.

To improve over this use second overloaded version of replace() i.e.

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

It will update the value of given key to newValue if its old value matches exactly to the given oldValue. If it updates it returns true, otherwise returns false.

// update value of frm to 888 from 99. It should return true
assert (mapOfWords.replace("frm", 99, 888) == true);

System.out.println(mapOfWords);

// update value of frm to 89 from 42. It should return false because
// old value of frm is not 89.
assert (mapOfWords.replace("frm", 89, 42) == false);

// update value of frmeee to 89 from 42. It should return false because
// key 'frmeee' does not exist in map
assert (mapOfWords.replace("frmeee", 89, 42) == false);

Complete example is as follows,

package com.thispointer.java.hashmap.examples;

import java.util.HashMap;


public class Example1 {
	
	public static void main(String[] args) {
		// Create a Map of words and their frequency count
		HashMap<String, Integer> mapOfWords = new HashMap<String, Integer>() {
			{
				put("John", 25);
				put("at", 2);
				put("from", 10);
				put("is", 5);
			}
		};
		// Print the map
		System.out.println(mapOfWords);

		/*
		 * Updating value of a given in HashMap using put()
		 */
		// Update the value of key "from" to 67, it will return the old value.
		Integer oldValue = mapOfWords.put("from", 67);

		System.out.println("Map Contens after change : ");
		// Print the map
		System.out.println(mapOfWords);
		// oldValue returned by put() should be 10.
		assert (oldValue == 10);

		// Now try to update a value in HashMap for key that don't even exists in
		// HashMap using put()
		oldValue = mapOfWords.put("frm", 99);
		
		// oldValue returned by put() should be null.
		assert (oldValue == null);

		// It will add a new key value Entry in HashMap
		System.out.println(mapOfWords);
		// But if put() returns null, we can not be sure that that it has added a new
		// entry in the map
		// or there was existing key in the map whose value was null.

		/*
		 * Updating value of a given in HashMap using replace()
		 */

		// Use replace() to avoid unnecessary addition to hashmap while updating value
		// of non existing key in hashmap.

		// Update the value of key "from" to 56, it will return the old value.
		oldValue = mapOfWords.replace("from", 56);

		assert (oldValue == 67);

		System.out.println(mapOfWords);

		// Now try to update a value in HashMap for key that don't even exists in
		// HashMap using replace()

		oldValue = mapOfWords.replace("frmee", 99);
		
		// It will NOT add the new key value entry in map and returns null.
	
		// oldValue returned by replace() should be null, because key dosn't exists in Map
		assert (oldValue == null);

		System.out.println(mapOfWords);

		// But if replace() returns null, we can not be sure that that there was no
		// entry in map with given key and it has not updating anything in map
		// or there was existing key in the map whose value was null.

		// Use replace() overloaded version to check if updation was successful or not

		/*
		 * Updating value of a given in HashMap using overloaded version of replace()
		 * public boolean replace(K key, V oldValue, V newValue)
		 */

		// It will update the value of given key to newValue if its old value matches
		// exactly to oldValue.
		
		// update value of frm to 888 from 99. It should return true
		assert (mapOfWords.replace("frm", 99, 888) == true);
		
		System.out.println(mapOfWords);
		
		// update value of frm to 89 from 42. It should return false because
		// old value of frm is not 89.
		assert (mapOfWords.replace("frm", 89, 42) == false);
		
		// update value of frmeee to 89 from 42. It should return false because
		// key 'frmeee' does not exist in map
		assert (mapOfWords.replace("frmeee", 89, 42) == false);
	}
}

Output:

{at=2, John=25, from=10, is=5}
Map Contens after change : 
{at=2, John=25, from=67, is=5}
{frm=99, at=2, John=25, from=67, is=5}
{frm=99, at=2, John=25, from=56, is=5}
{frm=99, at=2, John=25, from=56, is=5}
{frm=888, at=2, John=25, from=56, is=5}

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top