java 如何更新HashMap中键的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12596453/
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 for a key in HashMap?
提问by Vinesh
I am having HashMap like this,
我有这样的 HashMap,
HashMap<String,Set<String>> map = new HashMap<String,Set<String>>();
I am trying to do before adding an element in map
,
我正在尝试在添加元素之前做map
,
- Want to check whether the
key
exist or not, i can get it by usingmap.containsKey()
. - If the key exist, i want check the size of
Set
respective to that key. - If
size <= 1
i want add an element in that set.
- 想检查是否
key
存在,我可以通过使用map.containsKey()
. - 如果键存在,我想检查
Set
相应键的大小。 - 如果
size <= 1
我想在该集合中添加一个元素。
回答by Tudor
Sounds like this:
听起来像这样:
HashMap<String,Set<String>> map = new HashMap<String,Set<String>>();
Set<String> value = map.get("key");
if(value != null) {
if(value.size() <= 1) {
value.add("some value");
}
} else {
map.put("key", new HashSet<String>());
}
Now, either the last point was poorly worded (i.e. you want to update the Set associated with the key) or you really want to update the key itself, in which case you'd probably have to just remove it and add a new entry.
现在,要么最后一点措辞不当(即您想更新与密钥关联的 Set),要么您真的想更新密钥本身,在这种情况下,您可能只需要删除它并添加一个新条目。
回答by Peter Lawrey
I wouldn't use containsKey and get as this means two lookups when you only need one.
我不会使用 containsKey 和 get 因为这意味着当您只需要一个时进行两次查找。
private final Map<String,Set<String>> map = new HashMap<String,Set<String>>();
Set<String> set = map.get(key);
if(set != null && set.size() <= 1)
set.add(some$value);
The only problem with this is that the value will always be null
unless you set it somewhere so what you may want is
唯一的问题是,null
除非您将其设置在某处,否则该值将始终为
private final Map<String,Set<String>> map = new HashMap<String,Set<String>>();
Set<String> set = map.get(key);
if(value != null)
map.put(key, set = new HashSet<String>());
if (set.size() <= 1)
set.add(some$value);
It is unusual to have a set with a maximum size of 2. Is there any reason for this?
一个最大大小为 2 的集合是不寻常的。有什么原因吗?
回答by sabre_raider
You could get the set from the map with map.get(String key).
您可以使用 map.get(String key) 从地图中获取该集合。
Then test the size of the Set. If needed, add your element.
然后测试Set的大小。如果需要,请添加您的元素。
Now you can simply remove the old set from the map with map.remove(String key) and reinsert it with put(String, Set);
现在您可以简单地使用 map.remove(String key) 从地图中删除旧的集合并使用 put(String, Set) 重新插入它;