我有List
Map<String, Integer>
。每个Map
实例都包含productName作为键,产品价格作为值。
List<Map<String, Integer>> products = GET_ALL_PRODUCTS();
例如,List可以包含具有以下数据的地图:
地图1:
"prod1" : 10
"prod2" : 5
"prod3" : 2
地图2:
"prod3" : 3
"prod4" : 6
地图3:
"prod1" : 12
"prod4" : 8
我需要生成一个新的Map<String, Integer>
,其中包含productName作为密钥,但每个产品的累计价格金额为值。那就是:
新地图应包含:
"prod1" : 10+12
"prod2" : 5
"prod3" : 2+3
"prod4" : 6+8
我最终得到了以下代码,我想知道生成这个新Map
的最有效的方式是什么?
Map<String, Integer> cumulativeMap = new HashMap<String, Integer>();
for(int i=0; i< products.size(); i++){
Map<String, Integer> product = products.get(i);
...
}
答案 0 :(得分:5)
尝试,
List<Map<String, Integer>> products = new ArrayList<>();
//Add products Maps here
Map<String, Integer> cumulativeMap = new HashMap<String, Integer>();
// Use enhaced for loop for efficiency.
for(Map<String, Integer> productMap: products){
for(Map.Entry<String, Integer> p: productMap.entrySet()){
if(cumulativeMap.containsKey(p.getKey())){
cumulativeMap.put(p.getKey(), cumulativeMap.get(p.getKey())+ p.getValue());
}
else{
cumulativeMap.put(p.getKey(), p.getValue());
}
}
}