Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PriorityQueue sort by two values

Tags:

java

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!

like image 703
Johan Avatar asked Oct 21 '25 21:10

Johan


1 Answers

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);
like image 100
Alex Salauyou Avatar answered Oct 23 '25 10:10

Alex Salauyou