I have a List
of Map<String, Integer>
. Each Map
instance contain the productName as key, product price as value.
List<Map<String, Integer>> products = GET_ALL_PRODUCTS();
For example the List could contain Maps with the following data :
Map 1:
"prod1" : 10
"prod2" : 5
"prod3" : 2
Map 2:
"prod3" : 3
"prod4" : 6
Map 3:
"prod1" : 12
"prod4" : 8
I need to generate a new Map<String, Integer>
which contains productName as key still, but with the cumulative amount of price for each product as value. That is:
new Map should contain:
"prod1" : 10+12
"prod2" : 5
"prod3" : 2+3
"prod4" : 6+8
I ended up with the following code, I am wondering what is the most efficient way to generate this new Map
??
Map<String, Integer> cumulativeMap = new HashMap<String, Integer>();
for(int i=0; i< products.size(); i++){
Map<String, Integer> product = products.get(i);
...
}
Try,
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());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With