Sum value Of Class Objects Property In ArrayList

前端 未结 3 587
北恋
北恋 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:20

    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 data = new HashMap();
    
    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);
        }
    
    }
    }
    

提交回复
热议问题