使用集合删除重复列表 [英] Using collection to remove duplicate Lists
问题描述
我有 3 个列表,其中两个是重复的.我想将这些列表存储到一个单元中,删除所有重复项,所以我想将每个列表添加到一个集合中.这是我试过的:
I have 3 Lists, two of which are duplicates. I want to store these Lists into one unit, removing all the duplicates, so I was thinking to add each List to a collection. This is what I tried:
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".错误是有道理的,集合不知道如何比较每个列表以禁止重复.我需要覆盖比较方法吗?如果是这样,我该怎么做?这是解决这个问题的正确方法吗?
I get an error "java.util.Arrays$ArrayList cannot be cast to java.lang.Comparable". The error makes sense, the Collection doesn't know how to compare each list to disallow duplicates. Do I need to override a compare method? If so, How would I do that? Is this the correct approach to solving this problem?
谢谢!
推荐答案
制作一个 HashSet
并将所有内容添加到其中.
Make a HashSet
and add everything into that.
最后你将只剩下独特的元素
At the end you'll be left with just the unique elements
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;
然后你可以返回dedupedCollection;
作为没有重复的最终集合.
then you can return dedupedCollection;
as the final set with no duplicartes.
这篇关于使用集合删除重复列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!