Reputation: 331
I have an arraylist with the name of who pay something, and another arraylist with the cost of each payment. For example:
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:
Upvotes: 2
Views: 900
Reputation: 2935
The easiest way is to implement a Set<String>
as a LinkedHashSet<String>()
to preserve insert order. This will insure uniqueness in your set.
Sets check hashCode()
and the accompanying equals()
. Items are considered to be equal if their hashCode()
are their same.
If you implement your own class you can override hashCode()
and equals()
to check for uniqueness as well.
Upvotes: 0
Reputation: 394146
You are adding the entries of the Map
to the original List
s. You should clear them first:
nameArray.clear();
priceArray.clear();
for (Map.Entry<String, BigDecimal> entry : totals.entrySet()) {
nameArray.add(entry.getKey());
priceArray.add(entry.getValue());
}
Or, if you don't want to overwrite the original List
s, you should create new ArrayList
s.
Upvotes: 2