在哈希表中如何根据键更新值?

785
假设我们在Java中有一个 HashMap<String,Integer>
如何更新(递增)我找到的每个字符串键的整数值?
一种方法是删除并重新输入该对,但开销会成为一个问题。另一种方法是只放置新的一对,旧的将被替换。
在后一种情况下,如果我正在尝试插入一个新键时发生哈希码冲突会发生什么? 哈希表的正确行为应该是为其分配不同的位置,或者将其制作成当前桶中的列表。
17个回答

6

更加严谨的解决方案是避免NullPointerException:

map.replace(key, map.get(key) + 1);

8
如果键不存在,则 map.get(key) 会抛出 NPE 异常。 - Navendra
是的,那是真的。 - Sergey Dirin

5

由于声望不够,我无法评论一些答案,因此我将发布我应用的解决方案。

for(String key : someArray)
{
   if(hashMap.containsKey(key)//will check if a particular key exist or not 
   {
      hashMap.put(hashMap.get(key),value+1);// increment the value by 1 to an already existing key
   }
   else
   {
      hashMap.put(key,value);// make a new entry into the hashmap
   }
}

2
Integer i = map.get(key);
if(i == null)
   i = (aValue)
map.put(key, i + 1);

或者

Integer i = map.get(key);
map.put(key, i == null ? newValue : i + 1);

整数是原始数据类型,因此需要将其取出、处理,然后再放回。如果您有一个非原始数据类型的值,则只需要将其取出,处理,无需将其放回哈希映射表中。 http://cs.fit.edu/~ryan/java/language/java-data.html

1
感谢您提供这段代码片段,它可能会提供一些立即帮助。通过展示为什么这是解决问题的好方法,适当的解释将大大提高其教育价值,并使其对将来有类似但不完全相同的问题的读者更有用。请编辑您的答案以添加解释,并指出适用的限制和假设。 - Toby Speight
更正:Integer类不是原始数据类型,而是int原始类型的包装类。此外,由于Java8后的自动装箱,已经有一个被接受的答案在这里:https://dev59.com/Dm855IYBdhLWcg3ww3Wa#4158002 - mikerover

1
使用 for 循环来递增索引:
for (int i =0; i<5; i++){
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("beer", 100);

    int beer = map.get("beer")+i;
    System.out.println("beer " + beer);
    System.out ....

}

3
这只会在每次迭代中覆盖地图。请参考Matthew的回答以获得正确的方法。 - Leigh

1

1
使用Java8内置函数'computeIfPresent'
示例:
public class ExampleToUpdateMapValue {

    public static void main(String[] args) {
        Map<String,String> bookAuthors = new TreeMap<>();
        bookAuthors.put("Genesis","Moses");
        bookAuthors.put("Joshua","Joshua");
        bookAuthors.put("Judges","Samuel");

        System.out.println("---------------------Before----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
        // To update the existing value using Java 8
        bookAuthors.computeIfPresent("Judges", (k,v) -> v = "Samuel/Nathan/Gad");

        System.out.println("---------------------After----------------------");
        bookAuthors.entrySet().stream().forEach(System.out::println);
    }
}

0

尝试:

HashMap hm=new HashMap<String ,Double >();

注意:

String->give the new value; //THIS IS THE KEY
else
Double->pass new value; //THIS IS THE VALUE

你可以更改哈希表中的键或值,但不能同时更改两者。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接