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.

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

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

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

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,

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,

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

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

It will NOT add the new key value entry in map and returns 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.

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.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.