I have a object with 3 variable (id(string), year(int), pay(double))
I have created an arraylist that contains object.
So now I need to sum the the pay if they have the same id and year and store it in a new array! is that possible?
ArrayList<Earning> temp = new ArrayList();
ArrayList<Earning> temp = new ArrayList();
double tempEarning = 0.0;
int count = 0;
for (int i = 0; i < weeklyEarnings.size(); i++) {
Earning e = weeklyEarnings.get(i);
String id = e.getId();
int year = e.getYear();
tempEarning = e.getEarning();
Earning e2 = weeklyEarnings.get(i + 1);
if (id.equalsIgnoreCase(e2.getId()) && year == e2.getYear()) {
tempEarning += e2.getEarning();
} else {
Earning tempEarn = new Earning();
tempEarn.setEarning(tempEarning);
tempEarn.setId(id);
tempEarn.setYear(year);
temp.add(tempEarn);
count++;
tempEarning = 0.0;
}
}
weeklyEarnings.clear();
weeklyEarnings = temp;
temp.clear();
Can someone Help me? Thanks a lot!
Try this:
HashMap<String, Earning> totalEarnings = new HashMap<String, Earning>(); for (Earning earning : weeklyEarnings) { Earning tmpEarning = totalEarnings.get(earning.getId() + earning.getYear()); if (tmpEarning == null) { tmpEarning = new Earning(); tmpEarning.setId(earning.getId()); tmpEarning.setYear(earning.getYear()); totalEarnings.put(earning.getId() + earning.getYear(), tmpEarning); } tmpEarning.setEarning(tmpEarning.getEarning() + earning.getEarning()); } for (Earning earning : totalEarnings.values()) { System.out.println(earning.getId() + ' ' + earning.getyear() + ' ' + earning.getEarning()); }