Skip to content

Java HashMap Replace Example

This Java HashMap replace example shows how to replace a value for the given key using the replace method of the HashMap class. The example also shows the difference between the put and replace method.

How to replace a value in Java HashMap?

There are several ways using which you can replace a value associated with the key in the HashMap object.

1. Using the put method

The put method of the HashMap class replaces an old value with a new value for the given key if the key already exists in the map. It creates a new mapping if the key does not exist in the map.

The put method returns an old value associated with the given key if it exists in the map

Output

Tip: If the key does not exist in the map, the put method creates a new mapping for the specified key-value.

2. How to replace a value for given key using the replace method

The replace method of the HashMap class replaces an old value with the new value for a given key, if and only if the mapping exists for the given key.

The replace method returns the old value mapped to the given key if the mapping exists for the given key. It returns null if the key is not mapped to any value or if the key was mapped to the null value.

Output

3. How to replace a value for a given key only if it is mapped to a specified value

The replace method given above replaces a value for the given key if the key is mapped to any value in the map. What if you want to replace a value for the key if and only if it is mapped to a specific value in the map. In that case, you can use the overloaded replace method.

This replace method returns true if and only if the key is mapped to the oldValue in the map and replaced with the specified newValue. It returns false if the mapping for the key does not exist in the map or if the key is mapped to some other value.

Output

What is the difference between the put and replace methods?

The put method and replace method behaves the same if the key exists in the map. Both of them replace an old value with the new one and return the old value for the given key. But if the key does exist in the map, the put method creates a new mapping while the replace method returns null.

This example is a part of the HashMap in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.