Skip to content

Java TreeMap Replace Value for Key Example

This example shows how to replace a value for the given key in the TreeMap in Java. The example also shows how to replace a value in TreeMap using the put and replace methods.

How to replace a value for key in TreeMap in Java?

There are a couple of ways using which we can replace a value mapped to the given key in the TreeMap object.

1. Using the put method

The put method of the TreeMap class replaces an old value with the specified new value for the given key.

The put method returns the old value mapped to the specified key.

Output

Important Note: If the key does not exist in the TreeMap, the put method creates a new mapping in the map object.  Do not use this method to replace value if you do not want to add a new mapping to the TreeMap if the specified key does not exist.

2. Using the replace method

The replace method of the TreeMap class replaces an old value with the specified new value for the given key in the map.

The replace method also returns the old value mapped to the given key if the key exists in the TreeMap. If the key does not exist in the map or the key was previously mapped to a null value, the replace method returns null.

Output

How to replace a value for the key only if it is mapped to a specific value?

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

This replace method replaces the value of the key with newValue only if the key is mapped to the specified oldValue. This replace method returns true if the value is replaced for the key, false otherwise.

Output

This example is a part of the TreeMap In Java Tutorial.

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

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.