Using Priority Queue in Java

To create a priority queue in Java, use the PriorityQueue class. A priority queue returns elements by priority, not in the order they were added. By default, the smallest element comes first. Use the add() method to insert an element, peek() to get the first element, and poll() to get and remove it. In this Java Priority Queue Example, we add three numbers to a priority queue and remove the two smallest with poll(). Click Execute to run the Java Priority Queue Example online and see the result.
Using Priority Queue in Java Execute
 import java.util.PriorityQueue;

public class PriorityQueueDemo {
    public static void main(String[] args) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

        priorityQueue.add(10);
        priorityQueue.add(5);
        priorityQueue.add(20);

        System.out.println("Top element: " + priorityQueue.peek());

        System.out.println("Polled element: " + priorityQueue.poll());
      	System.out.println("Polled element: " + priorityQueue.poll());
    }
}

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

Updated: