Skip to content

How to Add Mappings to LinkedHashMap in Java Example

This example shows how to add elements to LinkedHashMap in Java. This example also shows how to add mappings (key-value pairs) to LinkedHashMap using put, putAll, and putIfAbsent methods.

How to add key-value mappings to LinkedHashMap in Java?

There are several ways using which you can add new key value mappings to a LinkedHashMap object as given below.

1. Add new key-value mapping using the put method

Use the put method of the LinkedHashMap class to add a key-value mapping to the LinkedHashMap object.

The put method associates the given key with the specified value in the LinkedHashMap object if the mapping does not exist for the key and returns null.

If the specified key is already mapped to any value in the map, the existing value is replaced with the specified new value and old value is returned.

Output

Important Note: The LinkedHashMap class allows null values to be associated with the key. Do not rely on the null return value of the put method to determine whether the key existed or not in the map.

A null value can also be returned by the put method if the given key was associated with a null value in the map.

Output

2. Using the putIfAbsent method

As we have seen in the above example, the put method replaces an old value with the new value if the key exists in the map. If you do not want to replace the value if the key exists. then use the putIfAbsent method.

The putIfAbsent method adds a new key-value mapping to the LinkedHashMap object if the key does not exist in the map and returns null. If the key exists in the map, it simply returns the value associated with the given key.

Output

Difference between put and putIfAbsent methods:

If the key does not exist in the LinkedHashMap object, both the put and putIfAbsent methods behave the same. Both of them add a key-value mapping to the map object.

But if the key exists, the put method replaces an old value with the new value but the putIfAbsent method does not.

3. Using the putAll method

The putAll method of the LinkedHashMap class copies all the mappings from the specified map to this LinkedHashMap object.

The putAll method also replaces all the values of a LinkedHashMap object with the values contained in the specified map for the mappings having the same key.

Output

You can also add all the mappings from the TreeMap using the putAll method as it accepts any Map object.

This example is a part of the Java LinkedHashMap tutorial with examples.

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

References:
Java 8 LinkedHashMap

About the author

Leave a Reply

Your email address will not be published.