I have BankDetails as pojo object with following variables and its getters and setters.
private String bankName;
private Map<String,Long[]> monthMap= newHashMap<String,Long[]>();
private String month;
now I have created List with each bean of BankDetails stored in list with multiple keys and values in its map eg
for one bean I have
map1 = 05, [8,0,0] ;map2 = 06, [6,0,4] ;map3 = 07, [45,3,0] ;map4 = 08, [0,56,9] ;
for second bean I have
map1 = 05, [0,0,0] ;map2 = 06, [8,0,4] ;map3 = 07, [5,0,1] ;map4 = 08, [2,6,8] ;
...
Where 05,06,07 and 08 are months.
now I want to have sum of all map1s map2s map3s and map4s from all beans vertically.
now, what I want is to have grandTotal monthly of array elements, of all List objects and return List which will have only 4 objects having total of all four as shown below.
map1- 05, [8, 0 ,0] ; map2- 06, [12,0,8] ; map3- 07,[50,3,1] : map4- 08, [2,62,17]
please suggest how can I do it. Being newBee in java really weak in iterations and logic.
You can do something like this:
// Declare a ArrayList of Map Objects
ArrayList<Map<String,Long[]>> mapsList = new ArrayList<>();
// add all the beans
mapsList.add(monthMap);
mapsList.add(monthMap2);
.
.
// declare a map for storing the sum
Map<String,Long[]> sumMap = new HashMap<>();
// for every key in map (assuming maps have the same amount
// of key-value pairs)
for(String str : mapsList.get(0).keySet()){
// initialising sum for long arrays
Long[] sum = {0L,0L,0L};
// for every map bean
for (int i = 0; i < mapsList.size(); i++){
// for every column in long array of map
for (int j = 0; j < mapsList.get(i).get(str).length; j++) {
sum[j] += mapsList.get(i).get(str)[j];
}
}
sumMap.put(str,sum);
}
I hope that helped.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.