I have a question on effective use of Java Comparator.
class MyClass {
//Active State: OPEN, PENDING, RUNNING
private String state;
private Date startDate;
private Date endDate;
}
Here the possible values of state field are OPEN, PENDING, RUNNING, CLOSED, CANCELLED etc., out of which OPEN, PENDING and RUNNING are the Active state. Now I want to write comparator which sorts the List<MyClass>, so that the active ones comes first and are sorted by startDate followed by non-active ones which are sorted based on endDate.
static final Set<String> ACTIVE;// this set contains OPEN, PENDING, RUNNING
List<MyClass> myList;//This is my list
...
Collections.sort(myList, new Comparator<MyClass>() {
@Override
public int compare(MyClass o1, MyClass o2) {
int c;
boolean isO2 = ACTIVE.contains(o2.getState());
boolean isO1 = ACTIVE.contains(o1.getState());
if (isO2 && isO1) {
c = DateTimeComparator.getInstance().compare(o2.getStartDate(), o1.getStartDate());
} else if (isO2) {
c = 1;
} else if (isO1) {
c = -1;
} else {
c = DateTimeComparator.getInstance().compare(o2.getEndDate(), o1.getEndDate());
}
return c;
}
});
My question is whether my above implementation of having single comparator good? or are there better ways to do it? Most likely I have to stick with Java 7 but solutions with Java 8 are welcome too.
MyClassas we don't own it, just simply using it. May be I need to ask the corresponding team to make it enum.