更新 java 地图条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1062135/
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
Updating a java map entry
提问by jrharshath
I'm facing a problem that seems to have no straighforward solution.
我面临一个似乎没有直接解决方案的问题。
I'm using java.util.Map
, and I want to update the value in a Key-Value pair.
我正在使用java.util.Map
,并且我想更新键值对中的值。
Right now, I'm doing it lik this:
现在,我正在这样做:
private Map<String,int> table = new HashMap<String,int>();
public void update(String key, int val) {
if( !table.containsKey(key) ) return;
Entry<String,int> entry;
for( entry : table.entrySet() ) {
if( entry.getKey().equals(key) ) {
entry.setValue(val);
break;
}
}
}
So is there any method so that I can get the required Entry
object without having to iterate through the entire Map
? Or is there some way to update the entry's value in place? Some method in Map
like setValue(String key, int val)
?
那么有没有什么方法可以让我获得所需的Entry
对象而不必遍历整个Map
?或者有什么方法可以更新条目的值?一些方法在Map
喜欢setValue(String key, int val)
吗?
jrh
jrh
采纳答案by skaffman
Use
用
table.put(key, val);
to add a new key/value pair or overwrite an existing key's value.
添加新的键/值对或覆盖现有键的值。
From the Javadocs:
来自 Javadocs:
V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
V put(K key, V value):将指定值与此映射中的指定键关联(可选操作)。如果映射先前包含键的映射,则旧值将替换为指定值。(当且仅当 m.containsKey(k) 返回 true 时,才称映射 m 包含键 k 的映射。)
回答by mkoeller
回答by Priyank
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
如果存在键,table.put(key, val)
则只会覆盖该值,否则会创建一个新条目。噗!你就完成了。:)
you can get the value from a map by using key is table.get(key);
That's about it
您可以通过使用键从地图中获取值,就是table.get(key);
这样