How to update the value on the map, if it exists, otherwise insert it

I did a search and was amazed that they had not asked before (at least I could not find him).

I have a map like this:

Map<String, String> myMap 

I know that I can check if a key exists on the map using containsKey(Object key); , and I can replace the value with replace(String key, String value); and, of course, put the value using put(String key, String value);

Now, if I want to check the value, if it exists, update it, otherwise insert it, I have to use the condition:

 if(myMap.containsKey(key)) { myMap.replace(key, value); } else { myMap.put(key, value); } 

Is there a better way to do this? I personally feel that this is a little redundant and too complicated, which could be one line, not five!

+7
java
source share
3 answers

Replace will be put() :

From the HashMap documentation

public V put (K key, V value) Associates the specified value with the specified key on this map. If the map previously contained a mapping for the key, the old value is replaced.

So you only need

 myMap.put(key, value); 
+12
source share

Removing all the code and below the line is enough.

 myMap.put(key, value); 

This already checks and replaces if any value already exists.

+4
source share

You can simply use the #put() method, it will replace the existing element, if any. By the way, AbstractMap (a superclass from HashMap ) implements #replace() as follows:

 default boolean replace(K key, V oldValue, V newValue) { Object curValue = get(key); if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) { return false; } put(key, newValue); return true; } 

In your case, you do not need additional checks of this method.

+2
source share

All Articles