Nick Ziebert
Nick Ziebert

Reputation: 1268

Using collection to remove duplicate Lists

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);

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?

Thanks!

Upvotes: 1

Views: 2328

Answers (3)

Salem
Salem

Reputation: 14917

Why not use a HashSet instead?

Lists already have a good hashCode implementation and a correct equals method.

Also, comparing Lists is not really logically possible - think about comparing two sets of numbers. How do I compare [2, 3, 8] with [1, 7, -2]?

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

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

//Now there are no duplicate lists.

Keep in mind that the lists must also have the same orderings, otherwise equals returns false. If you do not want this requirement you can also use a Set for your coins.

Upvotes: 2

Sandeep Kaul
Sandeep Kaul

Reputation: 3267

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;

then you can return dedupedCollection; as the final set with no duplicartes.

Upvotes: 2

Darshan Mehta
Darshan Mehta

Reputation: 30819

You can write your own comparator and pass that as an argument while creating the TreeSet, e.g.:

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());

Upvotes: 0

Related Questions