我有一个包含许多对象的ArrayList。我想对相同属性名称的值进行求和。
示例数据Array List为 ProfitAndLossDataDO的* 对象 *
Array List
"Michel" , 5000 "Alex" , 5000 "Edvin" , 4000 "Sosha" , 3000 "Michel" , 2000 "Alex" , 3000
结果将是(人相同时的值总和)-
"Michel" ,7000 "Alex" , 8000 "Edvin" , 4000 "Sosha" , 3000
逻辑类 ProfitAndLossDataDO
public class ProfitAndLossDataDO { String ledgerName; double ledgerAmount; public ProfitAndLossDataDO() { } public ProfitAndLossDataDO(String ledgerName, double ledgerAmount) { this.ledgerName = ledgerName; this.ledgerAmount = ledgerAmount; } public String getLedgerName() { return ledgerName; } public void setLedgerName(String ledgerName) { this.ledgerName = ledgerName; } public double getLedgerAmount() { return ledgerAmount; } public void setLedgerAmount(double ledgerAmount) { this.ledgerAmount = ledgerAmount; } @Override public String toString() { return ("ledger name : "+this.getLedgerName()+" Amount : "+this.getLedgerAmount()); } }
谢谢
我会遍历列表并将结果收集在地图中:
public static List<ProfitAndLossDataDO> sumPerLedgerName (List<ProfitAndLossDataDO> list) { Map<String, ProfitAndLossDataDO> 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()); }
编辑:
Java 8对Map接口的增强使我们能够以一种稍微更优雅的方式来实现此方法,if中间是令人讨厌的代码块:
Map
if
public static List<ProfitAndLossDataDO> sumPerLedgerName (List<ProfitAndLossDataDO> list) { Map<String, ProfitAndLossDataDO> 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()); }