每当有一个密钥匹配时,添加两个地图的值 [英] Adding values of two maps whenever there is a key match

查看:93
本文介绍了每当有一个密钥匹配时,添加两个地图的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一张地图,如

  {one = 1; 2 = 1;三= 1} 

另一个地图如

  {一个= 4; 2 = 4;我知道putAll()会添加唯一的键并替换现有的键。 
可以添加两个地图,这些地图会产生一个结果,比如在有现有的关键字时添加值。

  {一个= 5; 2 = 5;三= 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。创建小提琴此处


Say I have a map like

{one=1; two=1; three=1}

and another map like

{one=4; two=4; three=4}

I know that putAll() would add unique keys and replace existing keys. Will it be possible to do an addition of both the maps which would produce a result like adding the values whenever there is an existing keyword.

{one=5; two=5; three=5}

解决方案

Extend the HashMap and override the putAll method.

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);
 }

}

Now, create objects of MyMap instead of HashMap. Created a fiddle Here

这篇关于每当有一个密钥匹配时,添加两个地图的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆