0
0
JavaHow-ToBeginner · 4 min read

How to Use PriorityQueue in Java: Syntax and Examples

In Java, use PriorityQueue to store elements that are processed based on priority rather than insertion order. Create a PriorityQueue object, add elements with add(), and retrieve the highest priority element with poll() or peek().
📐

Syntax

The PriorityQueue class is part of java.util package. You create it by specifying the type of elements it will hold. It orders elements naturally or by a custom comparator.

  • PriorityQueue<Type> queue = new PriorityQueue<>(); creates a queue with natural ordering.
  • queue.add(element); adds an element.
  • queue.poll(); removes and returns the highest priority element.
  • queue.peek(); returns the highest priority element without removing it.
java
PriorityQueue<Type> queue = new PriorityQueue<>();
queue.add(element);
Type highest = queue.poll();
Type peeked = queue.peek();
💻

Example

This example shows how to create a PriorityQueue of integers, add numbers, and retrieve them in ascending order (natural order).

java
import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        queue.add(30);
        queue.add(10);
        queue.add(20);

        System.out.println("Elements in priority order:");
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}
Output
Elements in priority order: 10 20 30
⚠️

Common Pitfalls

Common mistakes include:

  • Assuming PriorityQueue keeps insertion order; it orders by priority instead.
  • Using peek() or poll() on an empty queue without checking, which returns null.
  • Not providing a comparator when using custom objects, causing ClassCastException.

Always check if the queue is empty before polling and provide a comparator for custom types.

java
import java.util.PriorityQueue;
import java.util.Comparator;

class Task {
    String name;
    int priority;

    Task(String name, int priority) {
        this.name = name;
        this.priority = priority;
    }
}

public class PriorityQueuePitfall {
    public static void main(String[] args) {
        // Wrong: No comparator, will throw ClassCastException
        // PriorityQueue<Task> queue = new PriorityQueue<>();

        // Right: Provide comparator to order by priority
        PriorityQueue<Task> queue = new PriorityQueue<>(Comparator.comparingInt(t -> t.priority));

        queue.add(new Task("Clean", 3));
        queue.add(new Task("Code", 1));
        queue.add(new Task("Sleep", 2));

        while (!queue.isEmpty()) {
            System.out.println(queue.poll().name);
        }
    }
}
Output
Code Sleep Clean
📊

Quick Reference

MethodDescription
add(E e)Adds element to the queue
poll()Removes and returns the highest priority element, or null if empty
peek()Returns the highest priority element without removing, or null if empty
isEmpty()Checks if the queue is empty
size()Returns the number of elements in the queue

Key Takeaways

PriorityQueue orders elements by priority, not insertion order.
Use poll() to remove and retrieve the highest priority element safely.
Provide a Comparator when using custom objects to avoid errors.
Always check if the queue is empty before polling or peeking.
PriorityQueue is useful for tasks like scheduling or sorting by priority.