Table of contents
1.
Introduction
2.
What are Priority Queues in Java?
3.
Hierarchy of PriorityQueue Class in Java
3.1.
Diagram: PriorityQueue Class Hierarchy in Java
4.
Declaration of Priority Queue using Java
5.
List of Methods in Java's PriorityQueue Class
6.
PriorityQueue Methods
6.1.
1. add()
6.2.
2. peek()
6.3.
3. poll()
6.4.
4. clear()
6.5.
5. contains()
6.6.
6. iterator()
6.7.
7. remove(obj)
6.8.
8. toArray()
7.
Frequently Asked Questions
7.1.
Which is the highest first priority queue in Java?
7.2.
Is Java PriorityQueue a min heap?
7.3.
Which data structure does a priority queue utilize?
7.4.
What is the insertion complexity for an element in the priority queue?
8.
Conclusion
Last Updated: Aug 13, 2025
Easy

PriorityQueue in Java

Author Saksham Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, a PriorityQueue is a part of the Java Collections Framework used to process elements based on their priority. Unlike regular queues, where elements are processed in FIFO (First-In-First-Out) order, a PriorityQueue processes elements with the highest priority first. It is commonly used in scheduling, task processing, and algorithms like Dijkstra's shortest path.

Heap and Priority Queue

What are Priority Queues in Java?

A PriorityQueue in Java is a queue data structure that orders elements according to their natural ordering or by a specified Comparator. It does not allow null elements and is unbounded, growing automatically as needed. Internally, it uses a binary heap to ensure efficient priority-based access.

Key characteristics:

  • Belongs to java.util package.
  • Implements Queue interface.
  • Elements are ordered based on priority, not insertion order.
  • Best for CPU scheduling, simulations, or real-time systems.

Hierarchy of PriorityQueue Class in Java

The PriorityQueue class follows this inheritance hierarchy:

java.lang.Object
   ↳ java.util.AbstractCollection<E>
       ↳ java.util.AbstractQueue<E>
           ↳ java.util.PriorityQueue<E>

Diagram: PriorityQueue Class Hierarchy in Java

                   +----------------+
                   |   Object       |
                   +----------------+
                            |
                            v
               +------------------------+
               | AbstractCollection<E>  |
               +------------------------+
                            |
                            v
               +---------------------+
               | AbstractQueue<E>    |
               +---------------------+
                            |
                            v
               +----------------------+
               | PriorityQueue<E>     |
               +----------------------+
                            |
                 +----------------------+
                 | Implements:          |
                 | Serializable,        |
                 | Iterable<E>,         |
                 | Collection<E>,       |
                 | Queue<E>             |
                 +----------------------+ 

While stacks have a last-in-first-out (LIFO mechanism) and queues have a first-in-first-out mechanism (FIFO), priority queues are somewhat different. Just by the name itself, a priority queue is just a queue — with the added extension of associating a “priority” to each item in the queue. Just like queues, priority queues also have a FIFO mechanism. But what does “priority” mean in this case? What does it mean to assign a “priority” to an item in the queue? 

Generally, the element’s value is considered for assigning the priority, i.e., its magnitude. For example, the element whose magnitude is highest is considered to be the element with the highest priority. However, in other cases, we can also mark an element with the lowest value as the element with the highest priority. Priorities can also be set by our needs.

priority queue

 

Thus we can classify them into two categories.

  1. Min Priority Queue: Minimum element has the highest priority.
  2. Max Priority Queue: Maximum element has the highest priority.

 

Now, this sounds very interesting but you must be thinking about how to implement it, the answer is a heap data structure. Heaps? What are they?

heap is a data structure based on trees where the root of the tree contains the element whose priority is the highest or the lowest. A heap is a complete binary treeAnother new word? Well, in a complete binary tree every node has two child nodes except the leaf nodes. This means all the leaf nodes should be at the same level and all other internal nodes should contain two child nodes each.

heap is a data structure based on trees

                                                

In the first image, all levels are filled and have two children except the leaf nodes, whereas if we look at the second image, some nodes don't have two children (node with value 3).

Also Read, Prefix Sum Array

Declaration of Priority Queue using Java

Now let’s talk about the declaration of priority queue using Java. We can use different constructors to declare our priority queue.

 

1. PriorityQueue(): Creates a PriorityQueue with the initial default capacity (11) that orders its elements according to their natural ordering.

PriorityQueue<E> pq = new PriorityQueue<E>();

 

2. PriorityQueue(Collection<E> c): Creates a PriorityQueue containing the elements in the specified collection.

PriorityQueue<E> pq = new PriorityQueue<E>(Collection<E> c);

 

3. PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.

 

PriorityQueue<E> pq = new PriorityQueue<E>(int initialCapacity);

4. PriorityQueue(int initialCapacity, Comparator<E> comparator): Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.

PriorityQueue<E> pq = new PriorityQueue(int initialCapacity, Comparator<E> comparator);

 

5. PriorityQueue(PriorityQueue<E> c): Creates a PriorityQueue containing the elements in the specified priority queue.

PriorityQueue<E> pq = new PriorityQueue(PriorityQueue<E> c);

 

6. PriorityQueue(SortedSet<E> c): Creates a PriorityQueue containing the elements in the specified sorted set.

PriorityQueue<E> pq = new PriorityQueue<E>(SortedSet<E> c);

 

Here ‘E’ refers to the type of element(Integer, String, etc.).

 

Let's now see some frequently used methods that are used to perform operations on the Priority Queue.

List of Methods in Java's PriorityQueue Class

Method Description
add(E e) Inserts the specified element into the queue. Throws exception if it fails.
clear() Removes all elements from the queue.
comparator() Returns the comparator used to order elements, or null for natural ordering.
contains(Object o) Returns true if the queue contains the specified element.
forEach(Consumer<? super E> action) Performs the given action for each element in the queue.
iterator() Returns an iterator over the elements in the queue.
offer(E e) Inserts the specified element into the queue. Returns false if it fails.
remove(Object o) Removes a single instance of the specified element from the queue.
removeAll(Collection<?> c) Removes all elements in the specified collection from the queue.
removeIf(Predicate<? super E> filter) Removes all elements satisfying the given predicate.
retainAll(Collection<?> c) Retains only the elements in the queue that are in the specified collection.
spliterator() Creates a late-binding and fail-fast Spliterator over the elements.
toArray() Returns an array containing all elements in the queue.
toArray(T[] a) Returns an array containing all elements, using the provided array type.

PriorityQueue Methods

1. add()

The add() method as the name suggests is used to add an element in the Priority Queue.

class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty priority queue.
        PriorityQueue<Integer> pQ = new PriorityQueue<Integer>();
 
        // Adding items to the pQueue using add() method.
        pQ.add(91);
        pQ.add(21);
 
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Time Complexity

O(log(N)), where ‘N’ is the number of elements in the priority queue.

 

Okay, now you have understood how to insert an element in the queue but how to access the topmost element?

We can do that easily by using the peek function. Let us understand it more by the following piece of code.

2. peek()

The peek() method simply returns the topmost element present in the priority queue.

 

class PriorityQueueDemo {
  
    // Main Method.
    public static void main(String args[])
    {
        // Creating an empty priority queue.
        PriorityQueue<Integer> pQ = new PriorityQueue<Integer>();
 
        // Adding items to the pQueue using add() method.
        pQ.add(88);
        pQ.add(98);
 
        // Printing the top element of PriorityQueue.
        System.out.println(pQ.peek());


 
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

98

 

Time Complexity

O(1)

 

What if I have to delete the topmost element?

To do that we can simply use the poll() function. Here is an example.

3. poll()

The poll() method deletes the topmost element of the priority queue.

public class PriorityQueueDemo {
 
    public static void main(String args[])
    {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
 
        pq.add(1);
        pq.add(2);
        pq.add(3);

        // Printing top element before deletion.
        System.out.println(pq.peek());

        
        // Using poll() to delete the topmost element.
        pq.poll();


        // Printing top element after deletion.             
        System.out.println(pq.peek());
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

3

2

 

Time Complexity

O(1)

4. clear()

It is used to remove all the elements from the priority queue.   

        PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
  
        // Adding elements to our priority queue.
        queue.add(15);        
        queue.add(10);
        
          
        // Displaying priority queue before clear().
        System.out.println(pq);
  
        // Using clear() to remove all elements          

        queue.clear();
  
        // After clear() the status of the priority queue.
        System.out.println(pq);
You can also try this code with Online Java Compiler
Run Code

 

Output

[15,12]

[] 

 

Time Complexity

O(N), where ‘N’ is the number of elements in the priority queue.

5. contains()

It is used to check if an element is present in the queue or not. If yes, it returns true, else returns false.

       PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
  
        // Adding elements to our priority queue.
        queue.add(15);        
        queue.add(10);
        
          
        // Displaying priority queue before clear().
        System.out.println(pq.contains(15));

        // Calling clear function
        pq.clear();
  
        // After clear() the status of the priority queue.
        System.out.println(pq.contains(2));
You can also try this code with Online Java Compiler
Run Code

 

Output

true

false

 

Time Complexity

O(1)

6. iterator()

It returns an iterator to iterate over the elements in the priority queue.

       PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
  
        // Adding elements to our priority queue.
        queue.add(15);        
        queue.add(10);
        
        // Assigning an iterator to the variable 'it'.
        Iterator it=pq.iterator();
        
        // Iterating over priority queue using iterator
        while (it.hasNext()) {
            System.out.println(it.next());
        }

 
You can also try this code with Online Java Compiler
Run Code

 

Output

15

10

7. remove(obj)

It removes the obj from the priority queue if present. If more than one obj is present, it will remove only one of them.

        PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
  
        // Adding elements to our priority queue.
        queue.add(15);        
        queue.add(10);

        queue.add(11);
        
          
        // Displaying priority queue before using remove().
        System.out.println(pq);

        // Calling clear function
        pq.remove(15);
  
        // After clear() the status of the priority queue.
        System.out.println(pq);
You can also try this code with Online Java Compiler
Run Code

 

Output

[15,11,10]

[11,10]

 

Time Complexity

O(1)

If the element is not present in the queue then the compiler throws an exception.

8. toArray()

It returns us an array containing all of the elements in the queue.

      PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
  
        // Adding elements to our priority queue.
        queue.add(15);        
        queue.add(10);

        queue.add(12);
        
          
        // Displaying priority queue before clear().
        System.out.println(pq);

 

        // Elements of the queue will be stored in array ‘arr’.
        Object[] arr = queue.toArray();
  
        // Printing the array
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
You can also try this code with Online Java Compiler
Run Code


Output

[15,12,10]

Frequently Asked Questions

Which is the highest first priority queue in Java?

Java’s PriorityQueue processes elements based on natural ordering or a custom comparator; to get highest-first, use a max-heap comparator.

Is Java PriorityQueue a min heap?

Yes, by default, Java’s PriorityQueue is a min-heap, where the smallest element has the highest priority and is polled first.

Which data structure does a priority queue utilize?

The priority queue makes use of a heap data structure. Depending upon the requirements, it can be either a min-heap or a max-heap.

What is the insertion complexity for an element in the priority queue?

The insertion complexity for an element in the priority queue is O(logN) where N is the size of the priority queue.

Conclusion

Now that you have mastered the basics of priority queue using Java and saw how we could use its inbuilt methods to perform different functions. 

Some Important Practice Problems on Priority Queue

  1. Rearrange the Array
  2. Sort A “K” Sorted Doubly Linked List 
  3. Merge K Sorted Arrays
  4. Matrix Median
  5. Implement a Priority Queue


Recommended Readings:

Live masterclass