Sum value Of Class Objects Property In ArrayList

纵饮孤独 提交于 2019-12-02 06:07:23

I'd iterate the list and collect the results in a map:

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

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

You can use a Hash Map as aleroot suggested. Use name as the key and sum as the value. Whenever you need to insert value just check such entry exists with the same key and update it.

public class ProfitAndLossDataDO {

HashMap<String, Double> data = new HashMap<String, Double>();

public ProfitAndLossDataDO() {

}

public void updateLedger(String ledgerName, double ledgerAmount) {
    double temp;
    if(data.containsKey(ledgerName)) {
        temp = data.get(ledgerName)+ledgerAmount;
        data.put(ledgerName,temp);
    }
    else {
        data.put(ledgerName,ledgerAmount);
    }

}
}

Why you don't just put them in an Map based collection with key/value pairs ?

I think that in this case a Map based collection is more suitable, for the data you have and the context in which you want to use it.

If you need to preserve the single items inside the list, you could use a linked list as Value of the map .

For example :

HashMap<String, LinkedList<Double>> cache = new HashMap<String, LinkedList<Double>>();

and SUM each element of the value LinkedList to find the total amount ... You could even wrap the LinkedList of doubles into a container object with helper functions like getTotal() or Sum().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!