给定具有getOrDefault的键的更新hashmap值

yay*_*zis 4 hashmap java-8

我有一个HashMap:

HashMap<string, Integer> hmap = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

我想在哪里增加HashMap值.为了避免nullPointer Exception如果密钥不存在,我检查一下!假设数据是:

//201803271 - 1000
//201803271 - 1000
//201803272 - 1000

//inside a loop i read the data...
  if (hmap.get("201803271") != null) {
      hmap.put("201803271", hmap.get("201803271") + 1000);
  }else{
      hmap.put("201803271", 1000);
  }
//end of loop
Run Code Online (Sandbox Code Playgroud)

这是有效的:

201803271 - 2000
201803272 - 1000
Run Code Online (Sandbox Code Playgroud)

但是,我读了这个问题如何在java hashmap中给出一个键来更新一个值?并且有一个使用Java 8方法的解决方案getOrDefault.我尝试过这个

hmap.put("201803271", count.getOrDefault("201803271", 1000) + 1000)
Run Code Online (Sandbox Code Playgroud)

但是,有了这个解决方案我得到错误的结果......

201803271 - 3000
201803272 - 2000
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Mis*_*sha 5

Java 8引入mergeMap仅针对此类问题进行接口的方法:

hmap.merge("201803271", 1000, Integer::sum);
Run Code Online (Sandbox Code Playgroud)

这意味着"为此密钥设置1000,但如果此密钥已经有值,则为其添加1000".

您的解决方案无法正常工作的原因是您默认获得1000,然后向其中添加1000.要正确执行此操作getOrDefault,您需要将0替换为0 in getOrDefault.hmap.put("201803271", count.getOrDefault("201803271", 0) + 1000))


ole*_*nik 5

你可以这样做:

map.put(key, map.getOrDefault(key, 0) + inc);
Run Code Online (Sandbox Code Playgroud)

或者

map.compute(key, (k, v) -> v == null ? inc : v + inc);
Run Code Online (Sandbox Code Playgroud)