更新 java 地图条目

发布于 2024-07-25 14:39:32 字数 624 浏览 4 评论 0原文

我面临着一个似乎没有直接解决方案的问题。

我正在使用 java.util.Map,并且我想更新键值对中的值。

现在,我正在这样做:

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;
        }
    }
}

那么有没有什么方法可以让我获得所需的Entry对象,而不必迭代整个Map? 或者有什么方法可以更新条目的值? Map 中的某些方法,例如 setValue(String key, int val)

杰瑞赫

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.

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)?

jrh

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

§普罗旺斯的薰衣草 2024-08-01 14:39:32

用于

table.put(key, val);

添加新的键/值对或覆盖现有键的值。

来自 Java 文档:

V put(K key, V value):将指定值与此映射中的指定键相关联(可选操作)。 如果映射先前包含键的映射,则旧值将替换为指定值。 (当且仅当 m.containsKey(k) 返回 true 时,映射 m 才被称为包含键 k 的映射。)

Use

table.put(key, val);

to add a new key/value pair or overwrite an existing key's value.

From the 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.)

清风无影 2024-08-01 14:39:32

如果 key 存在,table.put(key, val) 将只覆盖该值,否则它将创建一个新条目。 噗! 你就完成了。 :)

你可以使用 key is table.get(key); 从地图中获取值 就是这样

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. :)

you can get the value from a map by using key is table.get(key); That's about it

国际总奸 2024-08-01 14:39:32

您只需使用 方法

public Object put(Object key, Object value)

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文