1

我有一个数组列表,其中包含谁支付的名称,另一个数组列表包含每次付款的费用。例如:

  • 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 求和。我应该如何更正代码?

4

2 回答 2

2

您可以通过使用 aMap来存储每个人的姓名和他们购买的总金额来解决这个问题。

Map<String, Integer> totals = new HashMap<>();

for (int i = 0; i < nameArray.size(); ++i) {
    String name = nameArray.get(i);
    int price = priceArray.get(i);

    Integer total = totals.get(name);

    if (total != null) {
        totals.put(name, total + price);
    } else {
        totals.put(name, price);
    }
}

此时,您有一个Map包含每个人的条目以及他们花费的总金额。List您可以为每个创建新的 s Map.Entry,然后使用现有的排序代码。

List<String> uniqueNames = new ArrayList<>();
List<Integer> uniquePrices = new ArrayList<>();

for (Map.Entry<String, Integer> entry : totals.entrySet()) {
    uniqueNames.add(entry.getKey());
    uniquePrices.add(entry.getValue());
}

当然,您可以在从 构建列表时对列表进行排序entrySet(),但是您现在拥有的应该也可以工作。

于 2018-12-10T03:22:17.050 回答
0

您应该使用 HashMap 结合 List 来存储所有值:示例:

HashMap<String, List<Integer>> listNamesPrices = new HashMap<>();
List<Integer> nicolaPrices= new ArrayList<>();
nicolaPrices.add(24);
nicolaPrices.add(1);
listNamesPrices.put("Nicola", nicolaPrices);
int sum=0;
for (int i : prices){
    sum += i;
}
// sum will be 25 (24 + 1) at end, after that You can make another HashMap of <String, int>
// and store <"name",sum> in it, e.g. Nicola,25
HashMap<String, Integer> listNameSum = new HashMap<>();
listNameSum.put("Nicola",sum);
于 2018-12-10T00:40:36.647 回答