小编典典

ArrayList中类对象属性的总和

java

我有一个包含许多对象的ArrayList。我想对相同属性名称的值进行求和。

示例数据Array ListProfitAndLossDataDO的* 对象 *

      "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());
}
}

谢谢


阅读 389

收藏
2020-11-30

共1个答案

小编典典

我会遍历列表并将结果收集在地图中:

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());
}
2020-11-30