Random Quote

I have never understood the female capacity to avoid a direct answer to any question.

— Mr. Spock

Stack Exchange

profile for Andrea Girardi on Stack Exchange, a network of free, community-driven Q&A sites

Java: Sort a list of objects according to matching string/pattern

I need to sort a list of objects in which the matching items come up and others will go down so. For instance, a list of objects on which all the labels are in alphabetical order except for all the values that start with P that will be put on the top of the list.

I just need to create a new Comparator class instead of creating an anonymous Comparator, like this:

Collections.sort(result, new Comparator< MyObject>() {
    public int compare(final MyObject o1, final MyObject o2) {
        // Special case to put "P" in front of the list
        if(o1.getLabel().startsWith("P")) {
            return o1.getLabel().startsWith("P}")? o1.getLabel().compareTo(o2.getLabel()): -1;
        } else {
            return o2.getLabel().startsWith("P")? 1: o1.getLabel().compareTo(o2.getLabel());

On which MyObject is defined in this way:

class MyObject {
    private String label;
    private String value;
    // getter an setter