Introduction
The Java PriorityQueue class is one of the most useful implementations of the Queue interface in the Java Collection Framework. Unlike a normal queue, which processes elements in the order they are inserted (FIFO – First In, First Out), a PriorityQueue processes elements based on their priority.
The PriorityQueue class belongs to the java.util package and is commonly used in applications such as task scheduling, job processing, pathfinding algorithms, CPU scheduling, network routing, event management systems, and simulation software.
PriorityQueue does not maintain insertion order. Instead, it always ensures that the highest-priority (or lowest-priority, depending on the comparator) element is available at the front of the queue.
What is Java PriorityQueue?
A PriorityQueue is a queue implementation that orders its elements according to their priority rather than the order in which they were inserted.
By default:
- Smaller numbers have higher priority.
- Strings are sorted alphabetically.
- The element with the highest priority is always removed first.
For example:
Elements inserted:
30
10
20
40
Removal order:
10
20
30
40
Although 30 was inserted first, 10 is removed first because it has the highest priority according to natural ordering.
Key Characteristics
- Implements the Queue interface
- Uses a priority-based ordering
- Does not maintain insertion order
- Does not allow null elements
- Allows duplicate elements
- Dynamic size
- Not synchronized
- Uses a binary heap internally
Java PriorityQueue Hierarchy
Object
│
AbstractCollection
│
AbstractQueue
│
PriorityQueue
The PriorityQueue class implements the following interfaces:
- Queue
- Collection
- Iterable
- Serializable
Features of Java PriorityQueue
Some important features include:
- Processes elements based on priority
- Dynamic size
- Allows duplicate elements
- Does not allow null values
- Supports natural ordering
- Supports custom ordering using Comparator
- Efficient insertion and deletion
- Uses a binary heap data structure internally
- Supports Generic
Syntax
Import Statement
import java.util.PriorityQueue;
or
import java.util.*;
Creating a PriorityQueue
PriorityQueue<Integer> queue = new PriorityQueue<>();
Using the Queue interface:
Queue<Integer> queue = new PriorityQueue<>();
Constructors of PriorityQueue
1. Default Constructor
PriorityQueue<Integer> queue = new PriorityQueue<>();
Creates an empty priority queue using natural ordering.
2. Constructor with Initial Capacity
PriorityQueue<Integer> queue = new PriorityQueue<>(20);
Creates a PriorityQueue with an initial capacity of 20.
3. Constructor with Comparator
PriorityQueue<Integer> queue =
new PriorityQueue<>(Collections.reverseOrder());
Creates a PriorityQueue that processes elements in descending order.
4. Constructor Using Another Collection
List<Integer> numbers = Arrays.asList(40, 10, 20, 30);
PriorityQueue<Integer> queue =
new PriorityQueue<>(number);
Creates a PriorityQueue containing elements from another collection.
Common Methods of PriorityQueue
| Method | Description |
|---|---|
| offer() | Inserts an element |
| add() | Adds an element |
| poll() | Removes and returns the highest-priority element |
| remove() | Removes the highest-priority element |
| peek() | Returns the highest-priority element |
| element() | Returns the front element |
| peek() | Returns the highest-priority element |
| size() | Returns the number of elements |
| isEmpty() | Checks whether the queue is empty |
| contains() | Checks whether an element exists |
| clear() | Removes all elements |
Example 1: Creating a PriorityQueue
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(30);
queue.offer(10);
queue.offer(20);
System.out.println(queue);
}
}
Output
The internal representation may appear different, but the smallest element is always at the front.
Example 2: Removing Elements
import java.util.*;
public class PollExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(30);
queue.offer(10);
queue.offer(20);
while(!queue.isEmpty()){
System.out.println(queue.poll());
}
}
}
Output
20
30
Example 3: Using peek()
import java.util.*;
public class PeekExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(100);
queue.offer(40);
queue.offer(70);
System.out.println(queue.peek());
}
}
Output
Example 4: Descending Order
import java.util.*;
public class ReverseExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue =
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(10);
queue.offer(50);
queue.offer(30);
while(!queue.isEmpty()){
System.out.println(queue.poll());
}
}
}
Output
30
10
Example 5: PriorityQueue of Strings
import java.util.*;
public class StringExample {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer("Java");
queue.offer("Python");
queue.offer("C");
queue.offer("Spring");
while(!queue.isEmpty()){
System.out.println(queue.poll());
}
}
}
Output
Java
Python
Spring
Strings are processed in alphabetical order.
How PriorityQueue Works
Internally, Java PriorityQueue uses a binary heap.
Characteristics:
- Root node contains the highest-priority element.
- Insertion rearranges elements to maintain heap order.
- Deletion reorganizes the heap efficiently.
Because of this implementation:
- Insertion is efficient.
- Removal is efficient.
- Retrieving the highest-priority element is very fast.
| Feature | PriorityQueue | LinkedList Queue |
|---|---|---|
| Processing Order | Priority-based | FIFO |
| Insertion | Rear | Top |
| Maintains Insertion Order | No | Yes |
| Null Elements | Not Allowed | Allowed |
| Best For | Scheduling | Sequential processing |
| Internal Structure | Binary Heap | Doubly Linked List |
PriorityQueue vs TreeSet
| Feature | PriorityQueue | TreeSet |
|---|---|---|
| Duplicate Elements | Allowed | Not Allowed |
| Ordering | Priority-based | Sorted |
| Remove Smallest | Fast | Fast |
| Random Search | Slower | Faster |
Time Complexity
| Operation | Time Complexity |
|---|---|
| offer() | O(1) |
| poll() | O(1) |
| peek() | O(1) |
| search | O(n) |
| contains() | O(n) |
Real-life Example
Imagine you’re building a hospital emergency system.
Patients arrive in the following order:
Rahul (Priority 3)
Amit (Priority 1)
Neha (Priority 2)
Although Rahul arrived first, the treatment order becomes:
Amit
Neha
Rahul
This is because patients with higher medical priority are treated first.
Other real-world applications include:
- CPU scheduling
- Flight scheduling
- Task management
- Event simulation
- Network routing
- Job scheduling
- Pathfinding algorithms such as Dijkstra’s algorithm
- Online gaming matchmaking systems
Advantages of PriorityQueue
- Efficient priority-based processing
- Dynamic size
- Fast retrieval of the highest-priority element
- Supports custom sorting
- Allows duplicate elements
- Efficient heap implementation
- Supports Generics
- Well-suited for scheduling applications
Limitations of PriorityQueue
- Does not maintain insertion order
- Does not allow null elements
- Not synchronized
- Random access is not supported efficiently
- Iterating over the queue does not guarantee sorted order
Common Mistakes
1. Assuming FIFO Behavior
Incorrect assumption:
Inserted:
30
10
20
Expected removal:
30
10
20
Actual removal:
10
20
30
PriorityQueue always removes elements based on priority.
2. Adding Null Values
queue.offer(null);
This throws a NullPointerException.
3. Expecting Sorted Iteration
for(Integer num : queue){
System.out.println(num);
}
Iteration order is not guaranteed to be sorted. Use repeated poll() calls if you need elements in priority order.
4. Forgetting Comparator
Without a Comparator, natural ordering is always used.
5. Using PriorityQueue for FIFO Processing
If FIFO behavior is required, use LinkedList or ArrayDeque instead
Best Practices
- Declare variables using the Queue interface.
PriorityQueue<Integer> queue = new PriorityQueue<>();
- Use offer() and poll() instead of add() and remove() for safer operations.
- Provide a custom Comparator when natural ordering does not match your requirements.
- Avoid inserting null values.
- Use PriorityQueue only when priority-based processing is needed.
Conclusion
The Java PriorityQueue class is a powerful implementation of the Queue interface that organizes elements according to their priority instead of their insertion order. Its binary heap implementation provides efficient insertion, deletion, and retrieval operations, making it ideal for scheduling, simulation, graph algorithms, and other priority-driven applications.
Although it differs from a standard FIFO queue, PriorityQueue offers excellent performance for managing prioritized tasks.