我有一个数组列表,其中包含谁支付的名称,另一个数组列表包含每次付款的费用。例如:
- nameArray = 尼古拉,劳尔,洛伦佐,劳尔,劳尔,洛伦佐,尼古拉
- 价格数组 = 24、12、22、18、5、8、1
我需要总结每个人的成本。所以数组必须变成:
- nameArray = Nicola, Raul, Lorenzo
- price Array = 25, 35, 30 然后,按价格排序数组,所以:
- nameArray = 劳尔、洛伦佐、尼古拉
- 价格数组 = 35、30、25
我已经完成了订购部分,但我不知道如何将每个人的每个成本相加,然后删除重复的字符串/成本值。这是我的代码:
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 + 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);
}
}
}
我不能在行 totals.put(name, total + price); 上对 bigdecimal 求和。我应该如何更正代码?