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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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

Online Shopping