【问题标题】:Remove duplicates items from arraylist and hashmap从 arraylist 和 hashmap 中删除重复项
【发布时间】:2018-12-10 13:25:39
【问题描述】:

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

  • nameArray = 尼古拉、劳尔、洛伦佐、劳尔、劳尔、洛伦佐、尼古拉
  • priceArray = 24, 12, 22, 18, 5, 8, 1

我需要总结每个人的成本。所以数组必须变成:

  • nameArray = Nicola, Raul, Lorenzo

  • 价格数组 = 25、35、30

    然后,按价格排序数组,所以:

  • nameArray = 劳尔、洛伦佐、尼古拉

  • priceArray = 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.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());

}

这是日志的输出:

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]

尼科支付了 18.00 + 25.50 = 43.50,劳尔 16.98 +2 = 18.98 和洛伦佐 9.50。 名称和价格由用户动态插入。

我需要这样显示数组:

  • nameArray:尼科、劳尔、洛伦佐
  • priceArray: 43.50, 16.98, 9.50

【问题讨论】:

  • Set set = new LinkedHashSet(nameArray);或者简单地将nameArray作为Set,设置自动删除重复值

标签: java android arraylist hashmap


【解决方案1】:

您正在将Map 的条目添加到原始Lists。你应该先清除它们:

nameArray.clear();
priceArray.clear();
for (Map.Entry<String, BigDecimal> entry : totals.entrySet()) {
    nameArray.add(entry.getKey());
    priceArray.add(entry.getValue());
}

或者,如果您不想覆盖原来的Lists,您应该创建新的ArrayLists。

【讨论】:

  • 谢谢你,我已经用这段代码解决了:while(contLoop
【解决方案2】:

最简单的方法是将Set&lt;String&gt; 实现为LinkedHashSet&lt;String&gt;() 以保留插入顺序。这将确保您的集合中的唯一性。

设置检查hashCode() 和随附的equals()。如果 hashCode() 相同,则认为项目相同。

如果您实现自己的类,则可以覆盖 hashCode()equals() 以检查唯一性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多