2013-02-28 52 views
1

說我有一個地圖就像添加兩個地圖的價值,每當有一個關鍵的比賽

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

和其他地圖一樣

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

我知道的putAll()將添加唯一的密鑰和替換現有的密鑰。 是否有可能添加兩個地圖,這些地圖會產生一個結果,例如每當存在現有關鍵字時添加值。

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

是,約。 5-6行代碼。你有嘗試過什麼嗎? – jlordo 2013-02-28 13:17:59

+2

請看這裏http://stackoverflow.com/questions/11223561/how-can-i-sum-the-values-in-two-maps-and-return-the-value-using-guava – PSR 2013-02-28 13:20:11

+0

通過一張地圖,獲取第二張地圖中匹配鍵的值,將這兩個值相加並將其設置回第二張地圖。嘗試一下,讓我們知道結果。 – 2013-02-28 13:20:13

回答

0

延長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中的對象。創建小提琴Here

+1

但我相信'HashMap'中的實現可能會做更多的東西,這將被跳過這種重寫方法。 – 2013-02-28 13:36:18

+1

例如 - 我只是在某些情況下發現了一個'resize'方法在'putAll'中被調用。 – 2013-02-28 13:43:01

+0

@NishantShreshth用super.putAll更新了我的答案,以便我們的實現不會跳過實際的HashMap實現。 – 2013-02-28 13:52:38

0

試試這個,

   Map<String, Integer> map = new HashMap<String, Integer>(); 
    Map<String, Integer> map1 = new HashMap<String, Integer>(); 
      Map<String, Integer> map2 = new HashMap<String, Integer>(); 

    map.put("one", 1); 
    map.put("two", 1); 
    map.put("three", 1); 

    map1.put("one", 4); 
    map1.put("two", 4); 
    map1.put("three", 4); 


    for (Map.Entry<String, Integer> entry : map.entrySet()) { 
     System.out.println(map1.get(entry.getKey())+entry.getValue()); 
         map2.put(entry.getKey(),map1.get(entry.getKey())+entry.getValue()); 
    } 
0

試試這種方法。使用通用密鑰類型。當我們添加它們時,值類型仍爲Integer

public <K> void putAndAdd(Map<K, Integer> to, 
     Map<? extends K, ? extends Integer> from) { 
    for (Iterator<? extends Map.Entry<? extends K, ? extends Integer>> i = from 
      .entrySet().iterator(); i.hasNext();) { 
     Map.Entry<? extends K, ? extends Integer> e = i.next(); 
     if (to.get(e.getKey()) != null) { 
      to.put(e.getKey(), to.get(e.getKey()) + e.getValue()); 
     } else { 
      to.put(e.getKey(), e.getValue()); 
     } 
    } 
} 
相關問題