javacomparatortreeset

Java TreeSet remove duplicates based on object attribute


I wish to use TreeSet to remove duplicate object based on their attributes (here is toString() which return object's name ), here is my code :

Set<Object> s = new TreeSet<>(new Comparator<Object>() {          
            @Override
            public int compare(Object o1, Object o2) {
                if (o1.toString().equals(o2.toString())) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
s.addAll(listComCopy);
listComCopy.clear();
listComCopy.addAll(s);

listComCopy is a list of object.

It does the work but it only compares consecutive objects on the list, so if i have list(50).equals(list(150)) it will ignore.

Do you have any idea of how can i refactor this code to eliminate all duplicates regardeless their order in the list?


Solution

  • Your compare method does not adhere to the requirements.

    See Comparator.compare ...

    Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    You would be better off using String.compareTo in your compare.

        Set<Object> s = new TreeSet<>(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
            }
        });