我会遍历列表并将结果收集在地图中:
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中间是令人讨厌的代码块:
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());}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)