2014-12-06 115 views
1

如何將新地圖添加到現有地圖。地圖具有相同的類型Map<String, Integer>。如果新地圖中的密鑰存在於舊地圖中,則應添加值。什麼是合併兩幅地圖的最佳做法

Map<String, Integer> oldMap = new TreeMap<>(); 
Map<String, Integer> newMap = new TreeMap<>(); 

//Data added 

//Now what is the best way to iterate these maps to add the values from both? 
+0

另請參見[使用Java 8合併兩個映射](https://stackoverflow.com/questions/40158605/merge-two-maps-with-java-8) – Vadzim 2018-02-06 18:18:46

回答

4

由加載,我假設你要添加的整數值,而不是創建一個Map<String, List<Integer>>

在java 7之前,你必須迭代@laune顯示(+1給他)。否則,在Java 8中,Map上有一個合併方法。所以,你可以做這樣的:

Map<String, Integer> oldMap = new TreeMap<>(); 
Map<String, Integer> newMap = new TreeMap<>(); 

oldMap.put("1", 10); 
oldMap.put("2", 5); 
newMap.put("1", 7); 

oldMap.forEach((k, v) -> newMap.merge(k, v, (a, b) -> a + b)); 

System.out.println(newMap); //{1=17, 2=5} 

它是什麼,對於每個鍵值對,它融合了鍵(如果它尚未newMap,它只需創建一個新的鍵值對,否則它通過添加兩個整數更新現有密鑰保留的先前值)

也許你應該考慮使用Map<String, Long>來避免在添加兩個整數時發生溢出。

3
for(Map.Entry<String,Integer> entry: newMap.entrySet()) { 
    // get key and value from newMap and insert/add to oldMap 
    Integer oldVal = oldMap.get(entry.getKey()); 
    if(oldVal == null){ 
     oldVal = entry.getValue(); 
    } else { 
     oldVal += entry.getValue(); 
    } 
    newMap.put(entry.getKey(), oldVal); 
} 

希望這是你的意思

相關問題