我有一个 List
的 Map<String, Integer>
.每个Map
实例包含产品名称作为键,产品价格作为值。
List<Map<String, Integer>> products = GET_ALL_PRODUCTS();
例如,列表可以包含具有以下数据的 map :
map 1:
"prod1" : 10
"prod2" : 5
"prod3" : 2
map 2:
"prod3" : 3
"prod4" : 6
map 3:
"prod1" : 12
"prod4" : 8
我需要生成一个新的 Map<String, Integer>
其中仍然包含 productName 作为键,但每个产品的累计价格作为值。即:
新 map 应该包含:
"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);
...
}
最佳答案
尝试,
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());
}
}
}
关于java - 从 Map<String, Integer> 列表中获取累积值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20047009/