I did a search and was amazed this hadn't been asked before (at least I couldn't find it).
I have a map like this:
Map<String, String> myMap
I know that I can check if a key exists within the map usingcontainsKey(Object key);
and I can replace a value using replace(String key, String value);
and naturally put a value using put(String key, String value);
Now if I want to check a value if it exists update it, else insert it, I have to use a condition:
if(myMap.containsKey(key)) {
myMap.replace(key, value);
} else {
myMap.put(key, value);
}
Is there a better way of doing this? I personally feel the condition is a bit unnecessary and overcomplicating something which could be one line rather than five!
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.
We use the put() method with HashMap when we want to insert a value into the HashMap . And we can also use it to update the value inside the HashMap .
The replace will be done by put()
:
From the documentation of HashMap
public V put(K key, V value) Associates the specified value with the specified key in 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);
Remove all the code and below line is enough.
myMap.put(key, value);
That already checks and replaces if any value exist already.
You can just use the #put()
method, it will replace the existing item if there is one. By the way AbstractMap
(the superclass of HashMap
) implements #replace()
this way:
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 don't need the extra checks of this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With