I have few objects in a sheet object identified by ids , i want to merge these 3 objects by ids keeping in mind that all ids from all object should be there in the final sheet.
Although i can get all ids form object 1 serach in other object and add it , but i think there must be some smarter way of doing it .
Data @Data @NoArgsConstructor @AllArgsConstructor @Builder public class Data { int id ; int amount1 ; int amount2 ; int amount3 ;
}
Data data1 = new Data(7001,20,20,10);
Data data2 = new Data(8002,30,30,10);
Data data3 = new Data(7003,30,40,10);
List ls = new ArrayLisy();
ls.add(data1);
ls.add(data2);
ls.add(data3);
Map<String,List<Data>> localMap = new HashMap();
localMap.put("sheet1",ls);
Similary we have sheet2 and sheet3 with same or some different ids as
Data data1 = new Data(7001,5,0,2);
Data data2 = new Data(8004,2,2,2);
Data data3 = new Data(7003,3,4,5);
List ls = new ArrayLisy();
ls.add(data1);
ls.add(data2);
ls.add(data3);
Map<String,List<Data>> localMap = new HashMap();
localMap.put("sheet2",ls);
Now i just wand to Merge the Sheets to have one sheet with Sum of fields as
Final sheet data sheetFinal should have a list of Data like where id 7001 has amount1 added from all sheet (20 5) for amount1.
Data data1 = new Data(7001,25,20,12) ;
Data data2 = new Data(8002,30,30,10) ;
Data data3 = new Data(8004,2,2,2) ;
Data data4 = new Data(7003,33,44,20) ;
How can i merge the sheet by ids and get a final sheet with all data in a smarter and memory efficient way ? Thanks in
CodePudding user response:
Something like this? If its defined in the Data class we can lose the static and all the getters and setters.
public static List<Data> sum(Map<String, List<Data>> localMap) {
Map<Integer,Data> indexedAccumulator = new HashMap<>(); // indexed on Data.id
for(List<Data> localMapEntry: localMap.values()) {
for(Data data : localMapEntry) {
int id = data.getId();
if(indexedAccumulator.containsKey(id)) {
Data sumData = indexedAccumulator.get(id);
sumData.setAmount1(sumData.getAmount1() data.getAmount1());
sumData.setAmount2(sumData.getAmount2() data.getAmount2());
sumData.setAmount3(sumData.getAmount3() data.getAmount3());
} else {
indexedAccumulator.put(id, new Data(id, data.getAmount1(), data.getAmount2(), data.getAmount3())); // new object to preserve original
}
}
}
List<Data> sheetFinal = new ArrayList<>();
for (Data summedData : indexedAccumulator.values()) {
sheetFinal.add(summedData);
}
return sheetFinal;
}