PriorityQueue removes a least-ranked element according to its comparator, but equal-ranked elements have no specified removal order.
Java PriorityQueue: define tie order in the comparator
Specify the secondary key
Two jobs have the same urgency. A comparator that only compares urgency would leave their relative removal order unspecified. This queue compares urgency first, then receipt ID, producing a repeatable order for the example.
The queue's iterator does not expose priority order. Poll repeatedly if you need the ordered sequence, or copy the queue if the original must remain intact. PriorityQueue basics covers heap operations; comparator contracts covers transitivity and equality decisions.
Tie rules are business rules
Lexical ID order is only a deliberate fixture policy. A real scheduler may need submission sequence, deadline, fairness or tenant quotas. Encode those rules explicitly and test the rejected or equal-key cases.
Working program
import java.util.Comparator;
import java.util.PriorityQueue;
public class ReceiptReviewOrder {
static final class ReviewJob {
final String receiptId; final int urgency;
ReviewJob(String receiptId, int urgency) { this.receiptId = receiptId; this.urgency = urgency; }
}
public static void main(String[] args) {
PriorityQueue<ReviewJob> jobs = new PriorityQueue<>(
Comparator.comparingInt((ReviewJob job) -> job.urgency)
.thenComparing(job -> job.receiptId));
jobs.add(new ReviewJob("R-42", 1));
jobs.add(new ReviewJob("R-41", 1));
jobs.add(new ReviewJob("R-43", 2));
while (!jobs.isEmpty()) System.out.println(jobs.poll().receiptId);
}
}Output
R-41
R-42
R-43Costs and boundaries
Insertion and removal are O(log n) for n queued jobs; inspecting the head is O(1). Draining n jobs costs O(n log n). The queue does not provide stable ordering for comparator ties or sorted iterator order.
Common Mistakes
- Do not assume insertion order breaks priority ties.
- Do not print the iterator and call it sorted output.
- Do not subtract integer priorities in a comparator where overflow is possible.
Read next
Java PriorityQueue: ordered removal without a sorted list, Java comparators: tie-breakers, overflow and sorted-key identity, Java binary min-heap: sifting, fixed capacity and duplicate priorities.
