Java HashMap put example

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

How to add key-value mappings to HashMap using the put method?

The put method of the HashMap class adds specified key and value mapping to the map object.

If the specified key does not exist in the map, the put method maps the key with the given value and returns null. If the key is already mapped to any value in the map object, the old value is replaced with the specified new value and the old value is returned.

Output

How to add new mapping only if the key does not exist in the HashMap?

As you can see from the output if the key already exists in the map, the put method replaces an old value with the specified new value for a given key.

If want to add new mapping if the key does not exist but you do not want to replace the old value if the key already exists in the map, you can use the putIfAbsent method of the HashMap class.

The putIfAbsent method adds the specified key-value mapping to the map object if the key does not exist in the map or if the key is mapped to a null value. If the key is mapped to any non-null value in the map, the putIfAbsent method does nothing and returns the existing value mapped to the given key.

Output

Difference between put and putIfAbsent methods

If the key does not exist in the map, both put and putIfAbsent methods create a new mapping in the HashMap object. But if the key is already mapped to any non-null value in the map, the put method replaces an old value mapped to the specified key with the new value in the map while the putIfAbsent method does nothing.

Please also see Java HashMap get example and Java HashMap replace example to know more.

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

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

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