PC5
PC5

Reputation: 1

Can Java Sets test for duplicates elements without order mattering, when the elements are lists of integers?

I'm working with a Set<List<Integer>> and thought that it would be able to recognize duplicate lists, without order mattering (in the List<Integer>), but apparently it considers lists with the same elements and different orders as unique elements.

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

public class Test {

    public static void main(String[] args) {
        
        
        Set<List<Integer>> set = new HashSet();
        
        List<Integer> l1 = new ArrayList();
        List<Integer> l2 = new ArrayList();
        List<Integer> l3 = new ArrayList();
        
        l1.add(1);
        l1.add(2);
        set.add(l1);
        
        System.out.println(set);
        
        l2.add(1);
        l2.add(2);
        set.add(l2);
        
        System.out.println(set);
        
        l3.add(2);
        l3.add(1);
        set.add(l3);
        
        System.out.println(set);
        

    }
    


}

The output shows no change when adding a list with the same elements & order, but when order is reversed, it is considered unique:

[[1,2]]
[[1,2]]
[[1,2], [2,1]]

Is there some way to test, regardless of order, for duplicates? Originally, I was working with a list of list of integers List<List<Integer>>, so if there is some way to do so within that, that would be even better.

Upvotes: 0

Views: 144

Answers (2)

Parag Goel
Parag Goel

Reputation: 78

you can use containsAll() method available in the list before adding to the set. If it returns true don't add to the set.

Upvotes: 0

lists with the same elements and different orders

That's because

two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

If you want equality based on contents but not order, you are looking for something besides list equality. Perhaps you could use a Set. Otherwise, you'd need to write either a custom comparator (which would get extremely expensive; you could easily get into O(n^3 log n) territory) or a custom wrapper that kept a pair of lists, the original and a sorted copy for comparison.

Upvotes: 1

Related Questions