Video in progress

Strong Junior 🧺 Collections

Why do the elements look unsorted when you println a PriorityQueue?

PriorityQueue is a binary heap inside: only the smallest element is guaranteed to be at the head, and the rest are not fully sorted. toString and the iterator simply read the array in order.

📖 Answer

PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 8, 3, 2));
System.out.println(pq);        // for example [1, 2, 8, 5, 3]

while (!pq.isEmpty()) {
    System.out.print(pq.poll() + " ");  // 1 2 3 5 8
}

In a heap, every parent is smaller than its children, and that is all. poll() takes the head and restores the heap in O(log n). That is why the sorted sequence only comes out through poll.

Complexity: offer/poll are O(log n), peek is O(1), remove(Object) and contains are O(n).

Where it is used in practice: running tasks by priority, "top-K" problems (keep a min-heap of size K and drop the smallest ones), Dijkstra. If you need a max-heap: new PriorityQueue<>(Comparator.reverseOrder()).