PriorityQueue
PriorityQueue is a binary heap. offer and poll are O(log n). The head is the smallest element by natural order or by a comparator, not the first one you inserted.
Detailed Explanation
A queue usually means FIFO: first in, first out. A priority queue means "most important out first". PriorityQueue implements that with a binary heap in an array. The smallest element (or the one the comparator ranks first) sits at index 0. Removing it sifts the heap. Inserting sifts up.
Iteration order is not sorted. toString and the enhanced for walk the heap array. Only poll (or repeated peek plus remove) yields sorted order. If you need a sorted snapshot, copy to a list and sort, or use TreeSet if elements are unique.
The head is the least element. For a max-heap, pass Comparator.reverseOrder() or a reversed comparator. null is forbidden. Ties are broken arbitrarily; the heap is not stable. The class is not thread-safe. PriorityBlockingQueue is the concurrent sibling.
You reach for PriorityQueue when you always need the current min or max: Dijkstra's tentative distances, a job scheduler, "top k" with a heap of size k, merging k sorted streams. You keep ArrayDeque for FIFO. You keep TreeSet when you also need to delete an arbitrary element by value; deleting from a PriorityQueue is O(n) to find plus O(log n) to remove, and finding uses equals, not the comparator.
The cost of using it as a sorted collection is a wrong algorithm. The cost of a comparator that changes its mind is a broken heap. Do not mutate fields that affect ordering while the object is in the queue. There is no efficient "decrease key"; Dijkstra in the JDK style inserts a new node and ignores stale ones.
Capacity grows like ArrayList. peek is O(1). contains and remove(Object) are O(n). Size is O(1).
Code Examples
import java.util.PriorityQueue;
public class Soonest {
public static void main(String[] args) {
PriorityQueue<Integer> due = new PriorityQueue<>();
due.offer(30);
due.offer(10);
due.offer(20);
System.out.println(due.poll()); // prints: 10
System.out.println(due.poll()); // prints: 20
System.out.println(due.peek()); // prints: 30
}
}import java.util.Comparator;
import java.util.PriorityQueue;
public class Longest {
public static void main(String[] args) {
PriorityQueue<String> names = new PriorityQueue<>(
Comparator.comparingInt(String::length).reversed());
names.offer("bo");
names.offer("ana");
names.offer("c");
System.out.println(names.poll()); // prints: ana
}
}Common Gotchas
Iterating a `PriorityQueue` is not sorted
only repeated `poll` is.
`null` is not allowed
`offer(null)` throws `NullPointerException`.
`remove(x)` is O(n)
the heap is not a map. Keep extra indexes if you must delete by identity often.
Not thread-safe
use `PriorityBlockingQueue` or synchronize.