更新 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:58:57  来源:igfitidea点击:

Updating a java map entry

javamapin-place

提问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 Entryobject without having to iterate through the entire Map? Or is there some way to update the entry's value in place? Some method in Maplike 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

You just use the method

你只要用这个方法

public Object put(Object key, Object value)

if the key was already present in the Map then the previous value is returned.

如果键已经存在于 Map 中,则返回先前的值。

回答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);这样