java - 发生重复键时的 hashmap 自定义覆盖值

标签 java hashmap

我是 java 的新手,我有一个 HashMap ,我必须插入键作为年龄和值作为计数,即

         HashMap<Integer,Integer> hashMap = new HashMap<Integer, Integer>();
         hashMap.put(1,1);
         hashMap.put(2,1);
         hashMap.put(3,1);
         hashMap.put(1,1);  // whenever i insert this ,according to hashmap, it will override, but i want to customise like  the value should be incremented , ie the value of key 1 should be 2, again if i insert with  
         hashMap.put(1,1); // the value of key 1 should be 3.

我想自定义重写值,同时添加重复键。

我是按照下面的方式做的

         if(hashMap.containsValue(1)){
             Integer i = hashMap.get(1);
             i++;
             hashMap.put(1, i);
         }else{
             hashMap.put(1, 1);
         }  

还有比这更好的方法吗? 请建议

最佳答案

在 Java 8 中,您可以查看 Map.computeIfPresent() 方法:

hashMap.computeIfPresent(aKey, (k, v) -> v + 1);

关于java - 发生重复键时的 hashmap 自定义覆盖值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670850/

相关文章:

java - 如何设置 ImageView 占据屏幕的宽度?

java - 加密连接字符串,如何加密?

java - 如何在 JAX-WS Web 服务上引发自定义错误?

java - 单作者/单读者场景的 HashMap 或 ConcurrentHashMap?

java - 递归删除目录时的延迟

java - 每个循环的 Java 是否返回引用或引用副本?

java - HashMap 到 txt 文件 - 在 Java OOP 中写入键和值

java - 安卓 : HashMap is showing only last array item in a Listview field

java - 在 java 中,我想生成编译时错误而不是运行时错误

Java HashMap 将值存储在非预期的键中