Johan
Johan

Reputation: 53

PriorityQueue sort by two values

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!

Upvotes: 4

Views: 6976

Answers (2)

DerMike
DerMike

Reputation: 16190

Hava a look at https://stackoverflow.com/a/683049/197574

There the constructor public PriorityQueue(int initialCapacity, Comparator comparator) is used.

Your Coparator should contain something like this

if (this.emergency != other.emergency)
    return other.emergency - this.emergency
else
    return other.id - this.id

Upvotes: 0

Alex Salauyou
Alex Salauyou

Reputation: 14338

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);

Upvotes: 4

Related Questions