PriorityQueue
A queue that always hands out the smallest (or highest-priority) element.
Available since: Java 1.5
Syntax
public class PriorityQueue<E> extends AbstractQueue<E>Examples
Numbers come out in ascending order:
void main() {
Queue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 8, 3));
while (!pq.isEmpty()) {
IO.print(pq.poll() + " ");
}
IO.println("");
}Output:
1 3 5 8Tasks by priority with a comparator:
record Task(String name, int priority) {}
void main() {
var pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority).reversed());
pq.offer(new Task("email", 1));
pq.offer(new Task("bugfix", 5));
pq.offer(new Task("review", 3));
IO.println(pq.poll().name());
IO.println(pq.poll().name());
}Output:
bugfix
reviewNotes
offer() and poll() run in logarithmic time, peek() is instant. Printing the queue or iterating over it does not give sorted order — only the order of poll() is sorted. By default the smallest element comes out first; for the largest pass Comparator.reverseOrder().
See also
- Queue — A queue: elements are added at the tail and taken from the head.
- ArrayDeque — A fast array-based double-ended queue — a replacement for `Stack` and `LinkedList`.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- TreeSet — A set that keeps its elements in sorted order.
Related recipes
In the tutorial
- Queues and deques — Queues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.