Java PriorityQueue Syntax
PriorityQueue is a class in the java.util package. Without arguments, it orders elements by their natural order, so numbers come out from smallest to largest.
Java PriorityQueue Syntax
PriorityQueue<Type> queue = new PriorityQueue<>();
PriorityQueue<Type> queue = new PriorityQueue<>(comparator);
Is a Java PriorityQueue a min heap or a max heap?
By default, a PriorityQueue works as a min heap: peek() and poll() return the smallest element. To get the largest element first, pass Comparator.reverseOrder() to the constructor.
Java Priority Queue Examples
The following are examples of using a priority queue in Java. You can run any of these examples in the online Java code runner and add your own elements to see the order change.
Remove elements in priority order
poll() removes and returns the head each time, so the loop prints the numbers from smallest to largest. Printing the queue or looping over it with for-each does not give this order; only poll() does.
Java PriorityQueue poll() Example
import java.util.PriorityQueue;
public class PollExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(30);
queue.add(10);
queue.add(20);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
// output:
// 10
// 20
// 30
Create a max heap with Comparator.reverseOrder()
With a reversed comparator, the head is the largest element. peek() returns it without removing it, so size() still returns 3.
Java PriorityQueue Max Heap Example
import java.util.Comparator;
import java.util.PriorityQueue;
public class MaxHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
queue.add(30);
queue.add(10);
queue.add(20);
System.out.println(queue.peek());
System.out.println(queue.size());
}
}
// output:
// 30
// 3
Order objects with a custom Comparator
For objects without a natural order, pass a Comparator that compares the field you need. Here, the task with the lowest priority number comes out first.
Java PriorityQueue Comparator Example
import java.util.Comparator;
import java.util.PriorityQueue;
public class TaskQueueExample {
static class Task {
String name;
int priority;
Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
}
public static void main(String[] args) {
PriorityQueue<Task> tasks = new PriorityQueue<>(Comparator.comparingInt((Task t) -> t.priority));
tasks.add(new Task("Write tests", 2));
tasks.add(new Task("Fix bug", 1));
tasks.add(new Task("Update docs", 3));
while (!tasks.isEmpty()) {
System.out.println(tasks.poll().name);
}
}
}
// output:
// Fix bug
// Write tests
// Update docs
See also