Java PriorityQueue

A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play.

A few important points on Priority Queue are as follows:

  1. PriorityQueue doesn’t permit null.
  2. We can’t create a PriorityQueue of Objects that are non-comparable PriorityQueue are unbound queues.
  3. The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for the least value, the head is one of those elements — ties are broken arbitrarily.
  4. Since PriorityQueue is not thread-safe, java provides PriorityBlockingQueue class that implements the BlockingQueue interface to use in a java multithreading environment.
  5. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
  6. It inherits methods from AbstractQueue, AbstractCollection, Collection, and Object class.

Creating PriorityQueue

In order to create a priority queue, we must import the java.util.PriorityQueue package.


                        PriorityQueue<Integer> numbers = new PriorityQueue<>();
                    
ArrayDeque constructos

In order to create a ArrayDeque, we need to create an object of the ArrayDeque class. The ArrayDeque class consists of various constructors that allow the possible creation of the ArrayDeque. The following are the constructors available in this class.

Constructor Description Example
PriorityQueue() Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering. PriorityQueue pq = new PriorityQueue();
PriorityQueue(Collection c) Creates a PriorityQueue containing the elements in the specified collection. PriorityQueue pq = new PriorityQueue(Collection c);
PriorityQueue(int initialCapacity) Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering. PriorityQueue pq = new PriorityQueue(int initialCapacity)
PriorityQueue(int initialCapacity, Comparator comparator) PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator. PriorityQueue pq = new PriorityQueue(int initialCapacity, Comparator comparator)
PriorityQueue(PriorityQueue c) Creates a PriorityQueue containing the elements in the specified priority queue. PriorityQueue pq = new PriorityQueue(PriorityQueue c)
PriorityQueue(SortedSet c) Creates a PriorityQueue containing the elements in the specified sorted set. PriorityQueue pq = new PriorityQueue(SortedSet c)
Methods of PriorityQueue

The PriorityQueue class provides the implementation of all the methods present in the Queue interface.

Method Name Description
add() Inserts the specified element to the queue. If the queue is full, it throws an exception.
offer() Inserts the specified element to the queue. If the queue is full, it returns false.
peek() To access elements from a priority queue, we can use the peek() method.
remove() removes the specified element from the queue.
poll() returns and removes the head of the queue.
contains(element) Searches the priority queue for the specified element. If the element is found, it returns true, if not it returns false.
size() Returns the length of the priority queue.
toArray() Converts a priority queue to an array and returns it.
Basic Operations on PriorityQueue

The PriorityQueue class provides various methods to perform different operations on ArrayDeque. We will look at some commonly used ArrayDeque operations.

  1. ▪ Insert Elements to PriorityQueue
  2. ▪ Access PriorityQueue Elements
  3. ▪ Remove PriorityQueue Elements
  4. ▪ Iterating Over a PriorityQueue

Insert Elements to PriorityQueue

                        import java.util.PriorityQueue;

                        class Main {
                            public static void main(String[] args) {

                                // Creating a priority queue
                                PriorityQueue<Integer> numbers = new PriorityQueue<>();

                                // Using the add() method
                                numbers.add(4);
                                numbers.add(2);
                                System.out.println("PriorityQueue: " + numbers);

                                // Using the offer() method
                                numbers.offer(1);
                                System.out.println("Updated PriorityQueue: " + numbers);
                            }
                        }
                    
Access PriorityQueue Elements

                        import java.util.PriorityQueue;

                        class Main {
                            public static void main(String[] args) {
                        
                                // Creating a priority queue
                                PriorityQueue<Integer> numbers = new PriorityQueue<>();
                                numbers.add(4);
                                numbers.add(2);
                                numbers.add(1);
                                System.out.println("PriorityQueue: " + numbers);
                        
                                // Using the peek() method
                                int number = numbers.peek();
                                System.out.println("Accessed Element: " + number);
                            }
                        }
                    
Remove PriorityQueue Elements

                        import java.util.PriorityQueue;

                        class Main {
                            public static void main(String[] args) {
                        
                                // Creating a priority queue
                                PriorityQueue<Integer> numbers = new PriorityQueue<>();
                                numbers.add(4);
                                numbers.add(2);
                                numbers.add(1);
                                System.out.println("PriorityQueue: " + numbers);
                        
                                // Using the remove() method
                                boolean result = numbers.remove(2);
                                System.out.println("Is the element 2 removed? " + result);
                        
                                // Using the poll() method
                                int number = numbers.poll();
                                System.out.println("Removed Element Using poll(): " + number);
                            }
                        }
                    
Iterating Over a PriorityQueue

                        import java.util.PriorityQueue;
                        import java.util.Iterator;

                        class Main {
                            public static void main(String[] args) {

                                // Creating a priority queue
                                PriorityQueue<Integer> numbers = new PriorityQueue<>();
                                numbers.add(4);
                                numbers.add(2);
                                numbers.add(1);
                                System.out.print("PriorityQueue using iterator(): ");

                                //Using the iterator() method
                                Iterator<Integer> iterate = numbers.iterator();
                                while(iterate.hasNext()) {
                                    System.out.print(iterate.next());
                                    System.out.print(", ");
                                }

                                for(int value: numbers) {
                                  System.out.println(value);
                              }
                            }
                        }