简体   繁体   中英

Java Set - how to sort based on a list of names

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" ?

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM