1
class Obj{
    int x;
    int y;
    Date z;

    public int compareTo(Obj other) {
        if(this.z.getTime() > other.getZ().getTime())
            return 1;
        else if(this.z.getTime() < other.getZ().getTime())
            return -1;
        else 
            return 0;
    }

    boolean equals(Obj other) {
        if(x== other.x && y == other.y) 
            return true; 
        else 
            return false;
    }
}

Now I have a list<Obj> and I have to remove duplicate and only pick the latest one (latest z) when there are multiple object with same id.

sortedSet = new TreeSet(objList);
reversedSortedList = new ArrayList(sortedSet); //This will not be needed if we reverse the comparator logic. However it is not good. 
uniqueSet = new HashSet(reverseSortedList);
return uniqueSet;

Is this a good way of doing things. Or there is a cleaner and better way of doing things. Also the number of element in the list for me lies between 1000-10000

Thanks

2 Answers 2

0

You can write a separate Comparator to compare your object which will have the capability to sort in reverse(just opposite logic what you have implemented) instead of implementing compareTo method in our object(while I can see that your class doesn't implement Comparable interface).

In that way you will be able to directly get the reversely sorted Set and you can change the logic easily anytime you want or can use many different comparators at the different places.

For 1000-10000 using TreeSet is a good option with Compartors.

0

You comparator could be optimized to:

public int compareTo(Obj other) {
        return (int)(this.z.getTime() - other.getZ().getTime());
}
2
  • 1
    There will be a compile error in int compareTo since z.getTime() returns a long.
    – lkamal
    Nov 5, 2013 at 9:53
  • You can explicitly cast to int Nov 5, 2013 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.