I needed some help with a Java 8 solution to calculate totals.
Suppose that I have 3 item objects and each of these objects contain a list of (2 or 3) tax objects. Please find below a detailed imaging of this object -
Item 1
(List)
Tax 1 - Id-1 | Name-A | Desc | Amount-Rs.5 | More objects
Tax 2 - Id-2 | Name-B | Desc | Amount-Rs.10 | More objects
Tax 3 - Id-3 | Name-C | Desc | Amount-Rs.8 | More objects
Item 2
(List)
Tax 1 - Id-1 | Name-A | Desc | Amount-Rs.9 | More objects
Tax 3 - Id-3 | Name-C | Desc | Amount-Rs.10 | More objects
Now,
I have created a new Object (Aggregate) that needs to be the total based on Id
For ex: The above information should be have 3 aggregate objects with amounts summed
Tax-1 | Name-A | Desc | Amount-Rs.14
Tax-2 | Name-B | Desc | Amount-Rs.10
Tax-2 | Name-B | Desc | Amount-Rs.18
I was able to achieve this by looping through each object and adding it to a map <String Id,Object Aggregate>. If the keys existed, I would pull out the amount value from the Object Aggregate and add the amount to the existing amount. If not, I would create a new Aggregate object and add it to the map but I was hoping if there was a more optimised way to do this in Java 8
Global variable - Map<String, Aggregate> taxAggreg
for (Item item: Items) {
List < Tax > taxes = item.getTaxes;
for (Tax tax: taxes) {
createTax(Tax tax);
}
}
private void createTax(Tax tax) {
if (!taxAggreg.isEmpty() && taxAggreg.containsKey(tax.getTaxId())) {
Aggregate aggreg = taxAggreg.get(tax.getTaxId());
aggreg.setTaxAmount(aggreg.getTaxAmount().add(tax.getTaxAmount()));
taxAggreg.put(tax.getTaxId(), aggreg);
} else {
taxAggreg.put(tax.getTaxId(), new Aggregate(tax.getTaxId(), tax.getName(),
tax.getTaxAmount()));
}
}