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
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.
You comparator could be optimized to:
public int compareTo(Obj other) {
return (int)(this.z.getTime() - other.getZ().getTime());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.