Java 如果存在,如何更新地图中的值,否则将其插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31876857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update a value in a map if it exists else insert it
提问by Crazy Dino
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);
我知道我可以使用检查地图中是否存在一个键containsKey(Object key);
,我可以使用替换值replace(String key, String value);
并自然地使用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!
有没有更好的方法来做到这一点?我个人觉得这个条件有点不必要并且过于复杂,可能是一行而不是五行!
采纳答案by Jens
The replace will be done by put()
:
替换将通过put()
:
From the documentation of HashMap
来自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.
public V put(K key, V value) 将指定值与此映射中的指定键相关联。如果映射先前包含键的映射,则旧值将被替换。
So you only need
所以你只需要
myMap.put(key, value);
回答by Suresh Atta
Remove all the code and below line is enough.
删除所有代码,下面一行就足够了。
myMap.put(key, value);
That already checks and replaces if any value exist already.
如果已经存在任何值,它已经检查并替换。
回答by meskobalazs
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:
您可以只使用该#put()
方法,如果有,它将替换现有项目。顺便说一下AbstractMap
(的超类HashMap
)是这样实现的#replace()
:
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.
在您的情况下,您不需要此方法的额外检查。