我是 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/