【问题标题】:Using collection to remove duplicate Lists使用集合删除重复的列表
【发布时间】:2017-02-19 17:30:57
【问题描述】:

我有 3 个列表,其中两个是重复的。我想将这些列表存储到一个单元中,删除所有重复项,所以我想将每个列表添加到一个集合中。这是我尝试过的:

List<Integer> coins1 = Arrays.asList(5, 5, 10);
List<Integer> coins2 = Arrays.asList(5, 10, 5);
List<Integer> coins3 = Arrays.asList(10, 10);

coins1.sort((a, b) -> a.compareTo(b));
coins2.sort((a, b) -> a.compareTo(b));
coins3.sort((a, b) -> a.compareTo(b));

Collection<List<Integer>> allCoinPossibilities = new TreeSet();

allCoinPossibilities.add(coins1);
allCoinPossibilities.add(coins2);
allCoinPossibilities.add(coins3);

我收到错误消息“java.util.Arrays$ArrayList 无法转换为 java.lang.Comparable”。该错误是有道理的,集合不知道如何比较每个列表以禁止重复。我需要覆盖比较方法吗?如果是这样,我该怎么做?这是解决这个问题的正确方法吗?

谢谢!

【问题讨论】:

  • 您可以改用HashSet,因此没有订购要求。
  • 我认为不需要排序,至少 3 次。将一个列表放在一组中。另外两个检查集合。如果值存在则跳过,否则添加到集合。代码在幕后有很多开销
  • 我尝试了 allPossibilities.contains(coins) 而不是排序,但这种方法仍然会添加重复项。
  • @efekctive 如果你想使用equals,你确实需要对它们进行排序,因为它还会检查Lists 的顺序。
  • 让我返回代码。现在卡住了

标签: java arraylist collections


【解决方案1】:

创建一个HashSet 并将所有内容添加到其中。

最后你将只剩下独特的元素

List<Integer> coins1 = Arrays.asList(5, 5, 10);
List<Integer> coins2 = Arrays.asList(5, 10, 5);
List<Integer> coins3 = Arrays.asList(10, 10);

Set<Integer> dedupedCollection = new HashSet<Integer>();

dedupedCollection.add(coins1);
dedupedCollection.add(coins2);
dedupedCollection.add(coins3);

return dedupedCollection;

那么你可以return dedupedCollection;作为最终集,没有重复。

【讨论】:

  • 谢谢,这行得通。虽然我需要 new HashSet>() 你先回答。现在我的问题是我的递归方法很慢,但它有效。
【解决方案2】:

为什么不改用HashSet

Lists 已经有一个很好的hashCode 实现和一个正确的equals 方法。

另外,比较Lists 在逻辑上是不可能的——考虑比较两组数字。如何比较 [2, 3, 8][1, 7, -2]

Set<List<Integer>> noDuplicates = new HashSet<>();

noDuplicates.add(coins1);
noDuplicates.add(coins2);
noDuplicates.add(coins3);

//Now there are no duplicate lists.

请记住,列表也必须具有相同的顺序,否则 equals 返回 false。如果你不想要这个要求,你也可以为你的硬币使用Set

【讨论】:

    【解决方案3】:

    您可以编写自己的 comparator 并在创建 TreeSet 时将其作为参数传递,例如:

    class ListComparator implements Comparator<List<Integer>>{
    
        @Override
        public int compare(List<Integer> o1, List<Integer> o2) {
            // TODO comparison logic
            return 0;
        }
    
    }
    
    Collection<List<Integer>> allCoinPossibilities = new TreeSet(new ListComparator());
    

    【讨论】:

    • 你会如何建议为列表编写比较方法?
    • @1blustone 我们可以遍历列表并比较元素。
    • 这会比使用 Hashmap 更快吗? Hashmap 解决了我的问题,但是,我的代码运行速度太慢。它使用递归。
    猜你喜欢
    • 2015-11-24
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    相关资源
    最近更新 更多