PriorityQueue
About
A PriorityQueue is a queue in which each element is associated with a priority. The elements are ordered based on their priority, and elements with higher priority are dequeued before elements with lower priority. It is part of the java.utilpackage and implements the Queue interface.
Unlike a regular queue, which operates in a FIFO (First In, First Out) order, the PriorityQueue provides an ordering of elements according to their priority, where the element with the highest priority is dequeued first. By default, it orders elements according to their natural ordering (via Comparable), but a custom comparator can also be provided for custom ordering.
Elements of a priority queue may not be sorted. However, elements are always retrieved in sorted order.
Features
Unbounded:
PriorityQueueis typically unbounded, meaning it can grow dynamically as elements are added.Element Ordering: By default, elements are ordered in natural ascending order. However, a custom comparator can be provided for custom ordering.
Not Thread-Safe:
PriorityQueueis not thread-safe. If multiple threads will access the queue concurrently, external synchronization or usingPriorityBlockingQueueis needed.No Null Elements: Null elements are not allowed in
PriorityQueue. Attempting to insert anullwill throw aNullPointerException.Heap-Based Implementation: Internally,
PriorityQueueuses a heap (usually a binary heap) to maintain the ordering of elements.Custom Comparators: A custom comparator can be provided to define the priority ordering. This is useful for priority queues that are not based on natural ordering.
Efficient Insertions and Removals: Insertion (
add()) and removal (poll()) operations are efficient, with a time complexity of O(log n).Peeking at Head: The
peek()operation allows you to view the element with the highest priority without removing it from the queue.Support for Duplicates: The
PriorityQueueallows duplicates, unlike some other collections that may reject duplicates.
Key Methods
Method Type
Method
Description
Add Operations
add(E e)
Inserts the specified element into the priority queue.
offer(E e)
Inserts the specified element into the queue, returns false if full (rare).
Remove Operations
remove()
Removes a single instance of the specified element from the queue. This method differs from poll() only in that it throws an NoSuchElementException exception if this queue is empty.
poll()
Retrieves and removes the highest priority element from the queue. Or returns null if this queue is empty.
Access Operations
peek()
Retrieves the highest priority element without removing it.
element()
Retrieves the highest priority element without removing it. Throws exception if empty.
Size and Clearing
size()
Returns the number of elements in the priority queue.
clear()
Removes all elements from the priority queue.
Iterators
iterator()
Returns an iterator over the elements of the priority queue.
Big O Time Complexity for PriorityQueue Operations
Operation
Time Complexity
Details
Insert (add/offer)
O(log n)
Insertion in the heap structure.
Remove (poll/remove)
O(log n)
Removal of the root element (highest priority).
Peek (peek/element)
O(1)
Accessing the root element without removal.
Search (contains)
O(n)
Searching for an element requires scanning through the queue.
Size
O(1)
Retrieving the number of elements in the queue.
Iterator
O(n)
Iterating over all elements in the queue.
Example
Basic Operation
Using PriorityQueue for Task Scheduling (Max-Heap)
PriorityQueue for Sorting Elements
When to Use PriorityQueue ?
Task Scheduling: Use
PriorityQueueto schedule tasks where the priority of each task varies.Dijkstra’s Algorithm: Priority queues are commonly used in graph algorithms like Dijkstra’s shortest path algorithm.
Real-time Systems: When processing events with different priorities (e.g., priority messaging systems).
Merging Multiple Sorted Streams: Use
PriorityQueueto merge multiple sorted streams efficiently.
Last updated