I have a priority queue that contains Patients which look like this:
patientQueue.add(new Patient(idNr, name, emergencyNr));
Now I want to sort the Queue first by emergencyNr and then idNr. The `name´ doesn´t matter.
Right now I can sort the priority queue with comparable implemented in patient:
@Override
public int compareTo(Patient otherRequest) {
return Integer.compare(isEmergencyCase(), otherRequest.isEmergencyCase());
}
How can I implement an method that also sorts by IdNr? So if all EmergencyNr is equals then the lowest idNr will be first.
Thanks in advance guys!
Just add another condition in compareTo():
@Override
public int compareTo(Patient otherRequest) {
int r = Integer.compare(emergencyNr, otherRequest.emergencyNr);
return r == 0 ? Integer.compare(idNr, otherRequest.idNr) : r;
}
or use constructor that accepts Comparator, like:
Queue<Patient> q
= new PriorityQueue<>(CAPACITY, Comparator.comparing(Patient::getEmegencyNr)
.thenComparing(Patient::getIdNr));
P. S. To check correctness, use poll() instead of directly printing queue contents:
Patient p;
while((p = q.poll()) != null)
System.out.println(p);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With