I have an arraylist with the name of who pay something, and another arraylist with the cost of each payment. For example:
- nameArray = Nicola, Raul, Lorenzo, Raul, Raul, Lorenzo, Nicola
- priceArray = 24, 12, 22, 18, 5, 8, 1
I need to sum the cost of each person. So the array must become:
nameArray = Nicola, Raul, Lorenzo
price Array = 25, 35, 30
And then, ordering the array by price, so:
nameArray = Raul, Lorenzo, Nicola
priceArray = 35, 30, 25
I'm using a Map, but the problem now is that I see multiple times the name of each person and each payment with the sum. That's the code:
public void bubble_sort(ArrayList<String> nameArray, ArrayList<BigDecimal> priceArray) {
Map<String, BigDecimal> totals = new HashMap<>();
for (int i = 0; i < nameArray.size(); ++i) {
String name = nameArray.get(i);
BigDecimal price = priceArray.get(i);
BigDecimal total = totals.get(name);
if (total != null) {
totals.put(name, total.add(price));
} else {
totals.put(name, price);
}
}
for (Map.Entry<String, BigDecimal> entry : totals.entrySet()) {
nameArray.add(entry.getKey());
priceArray.add(entry.getValue());
}
for (int i = 0; i < priceArray.size(); i++) {
for (int j = 0; j < priceArray.size() - 1; j++) {
if (priceArray.get(j).compareTo(priceArray.get(j + 1)) < 0) {
BigDecimal tempPrice = priceArray.get(j);
String tempName = nameArray.get(j);
priceArray.set(j, priceArray.get(j + 1));
nameArray.set(j, nameArray.get(j + 1));
priceArray.set(j + 1, tempPrice);
nameArray.set(j + 1, tempName);
}
}
}
Log.v("New nameArray", nameArray.toString());
Log.v("New priceArray", priceArray.toString());
}
That's the output of the log:
New nameArray: [Nico, Nico, Raul, Nico, Raul, Lorenzo, Lorenzo, Raul]
New priceArray: [43.50, 25.50, 18.98, 18.00, 16.98, 9.50, 9.50, 2.00]
Nico paid 18.00 + 25.50 = 43.50, Raul 16.98 +2 = 18.98 and lorenzo 9.50. The name and the price were insert by the user dinamically.
I need to display the array like this:
- nameArray: Nico, Raul, Lorenzo
- priceArray: 43.50, 16.98, 9.50