Reputation: 62519
I have a java Set
and I can't change it to a TreeSet
although i could copy it over. Here is the issue:
I have names , tower, car, building , office , basement. I have a POJO which has a string label variable containing one of these for each instance.
how can i sort these to be the EXACT order of tower, car, building , office , basement. There will be no duplicates allowed of course(its a set).
public class Places{
String label;
int moreinfo;
}
so imagine I have 10 Places objects with labels that could be any of tower, car, building , office , basement: how can I sort these in a set to ensure that they are in the exact order of "tower, car, building , office , basement" ?
Upvotes: 0
Views: 279
Reputation: 376
You can use a Map to define an order for an arbitrary set of Strings:
private static Map<String, Integer> ordering;
static {
ordering = new HashMap<>();
ordering.add("tower", 1);
ordering.add("car", 2");
...add your other strings with increasing values...
}
Collections.sort(yourCollection, new Comparator<Places>() {
public int compare(Places p1, Places p2) {
return ordering.get(p1.label) - ordering.get(p2.label);
}
});
Be careful, however... you can't sort a Set. If it's a SortedSet (like a TreeSet) it will sort itself, if it's not it has no defined order.
Upvotes: 0
Reputation: 67
You could turn field 'label' into enum in which enum values are ordered by your custom order.
public enum Label {
TOWER, CAR, BUILDING, OFFICE, BASEMENT
}
Then, you can implement a comparable in order to sort the set.
class Places implements Comparable<Places>{
Label label;
int moreinfo;
@Override
public int compareTo(Places o) {
return label.compareTo(o.label);
}
}
You can then use Collections.sort method for your sorting.
Upvotes: 1