Skip to content

Java TreeMap Put Example

This example shows how to add key-value mappings to the TreeMap using the put method in Java. This example also shows how to add entries to TreeMap only if the key does not exist using the putIfAbsent method.

How to add key-value mappings to TreeMap using the put method in Java?

The put method of the TreeMap class adds specified key-value mappings to the TreeMap object.

The put method adds the specified key-value pair to the TreeMap and returns null if the specified key does not exist in the TreeMap object. If the key exists in the TreeMap, the put method replaces old value associated with the specified key with the new value and returns the old value.

Output

How to prevent replacement if the key already exists in the TreeMap?

As you can see from the output, the put method replaces an old value with the new value if the key already exists in the TreeMap. What if you do not want the replacement to happen and only want to add new mapping if the key does not exist in the TreeMap?

Well, in that case, you can use the putIfAbsent method instead of the put method.

The putIfAbsent method adds specified key-value mapping to the TreeMap if the key does not exist and returns null. If the key exists, the putIfAbsent method returns the existing value mapped to the given key.

Output

Difference between put and putIfAbsent methods

If the key does not exist in the TreeMap, both put and putIfAbsent methods behave the same. They both add key-value mapping to the map and return null.

However, when the specified key exists in the TreeMap, the put method replaces an old value with the new value while the putIfAbsent method does not replace.

Please also visit how to get value for the given key from TreeMap example.

This example is a part of the Java TreeMap Tutorial with Examples.

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.