假设我有一张像这样的 map
{one=1; two=1; three=1}
还有另一张 map ,例如
{one=4; two=4; three=4}
我知道 putAll() 会添加唯一键并替换现有键。 是否可以对两个映射进行相加,从而产生类似于只要存在现有关键字就添加值的结果。
{one=5; two=5; three=5}
最佳答案
扩展HashMap并重写 putAll 方法。
public class MyMap extends java.util.HashMap{
@Override
public void putAll(java.util.Map mapToAdd){
java.util.Iterator iterKeys = keySet().iterator();
while(iterKeys.hasNext()){
String currentKey = (String)iterKeys.next();
if(mapToAdd.containsKey(currentKey)){
mapToAdd.put(currentKey, new Integer(Integer.parseInt(get(currentKey).toString()) + Integer.parseInt(mapToAdd.get(currentKey).toString())));
}else{
mapToAdd.put(currentKey, get(currentKey));
}
}
super.putAll(mapToAdd);
}
public static void main(String args[]){
MyMap m1 = new MyMap();
m1.put("One", new Integer(1));
m1.put("Two", new Integer(2));
m1.put("Three", new Integer(3));
MyMap m2 = new MyMap();
m2.put("One", new Integer(4));
m2.put("Two", new Integer(5));
m2.put("Three", new Integer(6));
m1.putAll(m2);
System.out.println(m1);
}
}
现在,创建 MyMap 的对象而不是 HashMap。创建了一个 fiddle Here
关于java - 每当有键匹配时添加两个映射的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136508/