Question

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

Was it helpful?

Solution

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.

OTHER TIPS

You comparator could be optimized to:

public int compareTo(Obj other) {
        return (int)(this.z.getTime() - other.getZ().getTime());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top