I have several classes that implement the comparator interface for sorting an ArrayList by adding patient objects, I want to sort the list by several attributes and not have problems sorting only with Enums, however I want to override this view by sorting it using a boolean value. I know that I canβt use the method compareTo, since it is not a Wrapper class, but I cannot find a suitable way to sort the list through boolean.
Any help would be greatly appreciated.
public Patient(int nhsNumber, String name, Status triage, boolean previouslyInQueue, boolean waitingTime){
this.nhsNumber = nhsNumber;
this.name = name;
this.triage = triage;
this.previouslyInQueue = previouslyInQueue;
this.waitingTime = waitingTime;
}
This is my comparator class
public class PatientInQueueComparator implements Comparator<Patient> {
@Override
public int compare(Patient p1, Patient p2) {
if(p1.isPreviouslyInQueue() && !p2.isPreviouslyInQueue()){
return 1;
}else if(p1.isPreviouslyInQueue() && p2.isPreviouslyInQueue()){
return -1;
}
return 0;
}
My main method
List<Patient> queue = new ArrayList<Patient>();
queue.add(new Patient(1, "Bob", Status.URGENT, true, false));
queue.add(new Patient(2, "John", Status.EMERGENCY, false, false));
queue.add(new Patient(3, "Mary", Status.NON_URGENT, false, false));
queue.add(new Patient(4, "Luke", Status.SEMI_URGENT, false, true));
queue.add(new Patient(5, "Harry", Status.NON_URGENT, true, false));
queue.add(new Patient(6, "Mark", Status.URGENT, false, true));
System.out.println("*** Before sorting:");
for (Patient p1 : queue) {
System.out.println(p1);
}
Collections.sort(queue, new PatientComparator(
new PatientInQueueComparator(),
new PatientTriageComparator())
);
System.out.println("\n\n*** After sorting:");
for (Patient p1 : queue) {
System.out.println(p1);
}
Patient Comparator
private List<Comparator<Patient>> listComparators;
@SafeVarargs
public PatientComparator(Comparator<Patient>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
@Override
public int compare(Patient p1, Patient p2) {
for (Comparator<Patient> comparator : listComparators) {
int result = comparator.compare(p1, p2);
if (result != 0) {
return result;
}
}
return 0;
}