I have an ArrayList which having many objects. I want to do sum of values of the same property name.
Examples Data in Array List
which is Objects of
I'd iterate the list and collect the results in a map:
public static List sumPerLedgerName
(List list) {
Map map = new HashMap<>();
for (ProfitAndLossDataDO p : list) {
String name = p.getLedgerName();
ProfitAndLossDataDO sum = map.get(name);
if (sum == null) {
sum = new ProfitAndLossDataDO(name, 0.0);
map.put(name, sum);
}
sum.setLedgerAmount(sum.getLedgerAmount() + p.getLedgerAmount());
}
return new ArrayList<>(map.values());
}
EDIT:
Java 8's enhancements to the Map interface allow us to implement this method in a slightly more elegant way, with the annoying if
block in the middle:
public static List sumPerLedgerName
(List list) {
Map map = new HashMap<>();
for (ProfitAndLossDataDO p : list) {
String name = p.getLedgerName();
ProfitAndLossDataDO sum = map.computeIfAbsent(name, n -> new ProfitAndLossDataDO(n, 0.0));
sum.setLedgerAmount(sum.getLedgerAmount() + p.getLedgerAmount());
}
return new ArrayList<>(map.values());
}