Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get cumulative value from a List of Map<String, Integer>

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);
    ...
}
like image 662
Mellon Avatar asked Nov 18 '13 11:11

Mellon


1 Answers

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());
   }
  }
} 
like image 79
Masudul Avatar answered Sep 28 '22 04:09

Masudul