Sum value Of Class Objects Property In ArrayList

前端 未结 3 592
北恋
北恋 2021-01-25 04:56

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

3条回答
  •  遥遥无期
    2021-01-25 05:19

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

提交回复
热议问题