This post will discuss how to add values to a Map in Java.

1. Add values to a Map

The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map.

Download  Run Code

Output:

{Red=#FF0000, White=#FFFFFF, Black=#000000}

 
Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value. To avoid this behavior, use the putIfAbsent() method instead, which associates the specified key with the specified value if and only of the key is not already present in the map.

Download  Run Code

Output:

{Red=#FF0000, White=#FFFFFF, Black=#000000}

2. Add values to a MultiMap

There is no direct method to add a key-value pair to a map whose values are a mutable collection. However, you can do something like the below:

Download  Run Code

Output:

{Red=[#FF0000, #ff0000], White=[#FFFFFF, #ffffff, #FFF, #fff], Black=[#000000, #000]}

 
Note that UnsupportedOperationException is thrown if the underlying list is immutable. We can shorten the above code using the computeIfAbsent() method by Stream API.

Download  Run Code

Output:

{Red=[#FF0000, #ff0000], White=[#FFFFFF, #ffffff, #FFF, #fff], Black=[#000000, #000]}

That’s all about adding values to a Map in Java.