Java

Java PriorityQueue Explained with Practical Examples

Learn how Java PriorityQueue works, when to use it, how ordering is defined, and common pitfalls around iteration and custom comparators.

PriorityQueue is Java’s standard heap-backed queue. It is useful when you repeatedly need the smallest or highest-priority item without sorting the entire collection each time.

What PriorityQueue guarantees

By default, Java’s PriorityQueue is a min-priority queue. The element returned by peek() or removed by poll() is the smallest element according to natural ordering or a custom Comparator.

PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(30);
queue.add(10);
queue.add(20);

System.out.println(queue.poll()); // 10

Custom ordering

To create a max-priority queue, pass a reversed comparator.

PriorityQueue<Integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder());

For domain objects, compare the exact field that defines priority.

PriorityQueue<Task> tasks = new PriorityQueue<>(
    Comparator.comparingInt(Task::priority)
);

Iteration is not sorted

A common mistake is assuming that iterating over a PriorityQueue returns elements in priority order. It does not. Only peek() and poll() respect the queue’s priority guarantee.

If you need sorted output, repeatedly call poll() or copy the queue into a list and sort it.

Common use cases

  • Finding the top K elements
  • Merging sorted lists
  • Dijkstra’s shortest path algorithm
  • Scheduling jobs by priority
  • Processing events in timestamp order

Complexity

Insertion is O(log n). Removing the highest-priority element with poll() is also O(log n). Reading the current highest-priority element with peek() is O(1).

Use PriorityQueue when incremental priority access is more important than full sorted iteration.