Collections: PriorityQueue orders by priority, not insertion

A PriorityQueue keeps the smallest element (by its comparator) at the head. Note that toString shows heap order, so drain it with poll to see sorted output.

Code
record Task(String name, int priority) {}
var pq = new PriorityQueue<Task>(Comparator.comparingInt(Task::priority));

pq.add(new Task("email", 5));
pq.add(new Task("outage", 1));
pq.add(new Task("report", 3));

while (!pq.isEmpty()) {
    Task t = pq.poll();
    System.out.println(t.priority() + " " + t.name());
}
Output
1 outage
3 report
5 email
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30