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
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().