I had a problem in which I need to change the comparable value of a sorted set based on some condition.
Doing something like this:
SortedSet<T> groups;
for(T t: groups){
t.setOrdinal(max);
}
Will not automatically rearrange the SortedSet.
Reading online I figured out that I need to remove the object from the set and then add it again. Obviously, I cannot do it while iterating over the set. So I decided to make a Arraylist of the set. Make the set null and then add all the elements again so that they follow the sorted order. I did something like this:
SortedSet groups;
List<T> groupList = new ArrayList<T>(groups);
groups = null;
for(T t: groupList){
t.setOrdinal(max);
}
groups = new TreeSet<T>(groupList);
But when I check the groups set it didnt follow the sort order based on comparator which compared the ordinal of the object T
But when I tried something like this:
SortedSet groups;
List<T> groupList = new ArrayList<T>(groups);
groups.clear();
for(T t: groupList){
t.setOrdinal(max);
}
groups.addAll(groupList);
I got the result as expected. Can someone explain me whats happening?
This is how I have implemented my class T
public class T implements Serializable, Comparable<T> {
//
int ordinal;
//getter
//setter
@Override
public int compareTo(T that) {
if (that == null) {
return 1;
}
return this.ordinal - that.ordinal;
}
}
For those want to see complete program:
List<SmartUser> groupsList = new ArrayList<SmartUser>(groups);
groups = null;
for (SmartUser smartUser : groupsList) {
if (smartUser.isExpired()) {
smartUser.setOrdinal(Long.MAX_VALUE);
}
SmartUserQuery smartUserQuery = smartUser.getSmartUserQuery();
if (smartUserQuery != null) {
//Do parallel processing: of each samrtUser
}
}
groups = new TreeSet<SmartUser>groupsList;
Correct result giving approach:
List<SmartUser> groupsList = new ArrayList<SmartUser>(groups);
groups.clear();
for (SmartUser smartUser : groupsList) {
if (smartUser.isExpired()) {
smartUser.setOrdinal(Long.MAX_VALUE);
}
SmartUserQuery smartUserQuery = smartUser.getSmartUserQuery();
if (smartUserQuery != null) {
//Do parallel processing: of each samrtUser
}
}
groups.addAll(groupsList);
Thanks.