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.

Declaration

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

where E is the type of elements held in this queue

Important points

  • PriorityQueue doesn’t permit null.

  • We can’t create a PriorityQueue of Objects that are non-comparable

  • PriorityQueue are unbound queues.

  • 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.

  • Since PriorityQueue is not thread-safe, java provides PriorityBlockingQueue class that implements the BlockingQueue interface to use in a java multithreading environment.

  • The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

  • It provides O(log(n)) time for add and poll methods.

  • It inherits methods from AbstractQueue, AbstractCollection, Collection, and Object class.

Constructors

PriorityQueue()

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

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

PriorityQueue(Collection c)

Creates a PriorityQueue containing the elements in the specified collection.

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

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);

PriorityQueue(int initialCapacity, Comparator 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);

PriorityQueue(PriorityQueue c)

Creates a PriorityQueue containing the elements in the specified priority queue.

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

PriorityQueue(SortedSet c)

Creates a PriorityQueue containing the elements in the specified sorted set.

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

Methods

METHODDESCRIPTION
add(E e)Inserts the specified element into this priority queue.
clear()Removes all of the elements from this priority queue.
comparator()Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements.
contains​(Object o)Returns true if this queue contains the specified element.
forEach​(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
iterator()Returns an iterator over the elements in this queue.
offer​(E e)Inserts the specified element into this priority queue.
remove​(Object o)Removes a single instance of the specified element from this queue, if it is present.
removeAll​(Collection c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
retainAll​(Collection c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this queue.
toArray()Returns an array containing all of the elements in this queue.
toArray​(T[] a)Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.

Operations

Adding Elements

In order to add an element in a priority queue, we can use the add() method. The insertion order is not retained in the PriorityQueue. The elements are stored based on the priority order which is ascending by default.

/*package whatever //do not write package name here */

import java.util.*;
import java.io.*;
	
public class PriorityQueueDemo {
	
	public static void main(String args[])
	{
		PriorityQueue<Integer> pq = new PriorityQueue<>();
		for(int i=0;i<3;i++){
			pq.add(i);
			pq.add(1);
		}
		System.out.println(pq);
	}
}

Output

[0, 1, 1, 1, 2, 1]

Removing Elements

In order to remove an element from a priority queue, we can use the remove() method. If there are multiple such objects, then the first occurrence of the object is removed. Apart from that, the poll() method is also used to remove the head and return it.

// Java program to remove elements
// from a PriorityQueue

import java.util.*;
import java.io.*;

public class PriorityQueueDemo {

	public static void main(String args[])
	{
		PriorityQueue<String> pq = new PriorityQueue<>();

		pq.add("Tit");
		pq.add("For");
		pq.add("Tat");

		System.out.println("Initial PriorityQueue " + pq);

		// using the method
		pq.remove("Tit");

		System.out.println("After Remove - " + pq);

		System.out.println("Poll Method - " + pq.poll());

		System.out.println("Final PriorityQueue - " + pq);
	}
}

Output

Initial PriorityQueue [For, Tit, Tat]
After Remove - [For, Tat]
Poll Method - For
Final PriorityQueue - [Tat]

Accessing the elements

Since Queue follows the First In First Out principle, we can access only the head of the queue. To access elements from a priority queue, we can use the peek() method.

// Java program to access elements
// from a PriorityQueue
import java.util.*;

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

		// Creating a priority queue
		PriorityQueue<String> pq = new PriorityQueue<>();
		pq.add("Tit");
		pq.add("For");
		pq.add("Tat");
		System.out.println("PriorityQueue: " + pq);

		// Using the peek() method
		String element = pq.peek();
		System.out.println("Accessed Element: " + element);
	}
}

Output

PriorityQueue: [For, Tit, Tat]
Accessed Element: For

Iterating the PriorityQueue

There are multiple ways to iterate through the PriorityQueue. The most famous way is converting the queue to the array and traversing using the for loop. However, the queue also has an inbuilt iterator which can be used to iterate through the queue.

// Java program to iterate elements
// to a PriorityQueue

import java.util.*;

public class PriorityQueueDemo {

	// Main Method
	public static void main(String args[])
	{
		PriorityQueue<String> pq = new PriorityQueue<>();

		pq.add("Tit");
		pq.add("For");
		pq.add("Tat");

		Iterator iterator = pq.iterator();

		while (iterator.hasNext()) {
			System.out.print(iterator.next() + " ");
		}
	}
}

Output

PriorityQueue: [For, Tit, Tat]
Accessed Element: For
core java programming collections priorityqueue

Subscribe For More Content