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>() {
@Override
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
}