Showing posts with label PriorityQueue. Show all posts
Showing posts with label PriorityQueue. Show all posts

PriorityQueue based on custom Priority setting

Just by name "Queue" we can think of big "Q" for Movie tickets booking in our olden days or have read about FIFO order. But here "PriorityQueue" is little different and it follows same Queue functionality with Priority items are out first.
Lets take scenario where there are lot of incoming tickets in support system with multiple priorities (CRITICAL, HIGH, MEDIUM, LOW). Here support team needs to serve all tickets based on their priority than their logged order, like critical priorities first and then high, medium and low priority tickets at last.
Lets see simple example class which takes multiple Tickets along with priority and while we are reading critical tickets 1st, high tickets 2nd, medium tickets 3rd and low priority tickets at last.

 * Simple Ticket class takes input as ticket number, Ticket details
 * along with priority of each ticket
public class Ticket implements Comparable<Ticket>{
 enum Priority{
 private int ticketId;
 private String task;
 private Priority priority;
 public Ticket(int ticketId, Priority priority, String task) {
  this.ticketId = ticketId;
  this.task = task;
  this.priority = priority;
 public String toString() {
  return ticketId +" : "+task;
 public int compareTo(Ticket o) {
  return this.priority.compareTo(o.priority) ;

import java.util.PriorityQueue;
import java.util.Queue;

import com.pract.Ticket.Priority;

public class PriorityQueueExample {

 public static void main(String[] args) {
  // Adding 6 Tickets with different priority 
  Queue<Ticket> ticketQueue = new PriorityQueue<Ticket>();
  ticketQueue.offer(new Ticket(1, Priority.LOW, "Low priority task - Cleanup activity"));
  ticketQueue.offer(new Ticket(2, Priority.MEDIUM, "Medium priority task - Taking dump"));
  ticketQueue.offer(new Ticket(3, Priority.HIGH, "High priority task - Production update"));
  ticketQueue.offer(new Ticket(4, Priority.MEDIUM, "Medium priority task - Testing"));
  ticketQueue.offer(new Ticket(5, Priority.HIGH, "High priority task - Important bug fixing"));
  ticketQueue.offer(new Ticket(6, Priority.CRITICAL, "Critical priority task - Hacker Thread"));
  * Listing tickets based on priority like 
  * CRITICAL, HIGH, MEDIUM and then LOW tickets.
 private static void listTicketsBasedOnPriority(Queue<Ticket> tickets){
  while (!(tickets.isEmpty()))


6 : Critical priority task - Hacker Thread
5 : High priority task - Important bug fixing
3 : High priority task - Production update
2 : Medium priority task - Taking dump
4 : Medium priority task - Testing
1 : Low priority task - Cleanup activity

Here in output we can see list of tickets printed by priority order wise.

PriorityQueue in Java

PriorityQueue in Java

PriorityQueue is unbounded priority queue based on priority heap. 
  • Basically PriorityQueue are ordered according to natural ordering or by a Comparator provided at queue construction time, depending on which constructor is used. 
  • Another important that PriorityQueue won't take null value as input. 
  • Since PriorityQueue reply on natural ordering it won't take non-comparable object as input which will throw ClassCastException
  • Internally memory size will be managed automatically as and when elements added to the PriorityQueue.
  • By using Iterator interface its not guaranteed to traverse the elements of the PriorityQueue in any particular order. For ordered traversal need to use Arrays.sort(pq.toArray()). 
  • By implementation PriorityQueue is not synchronized and non-thread safe. Suppose if we need synchronized/thread-safe Queue then we need to go for PriorityBlockingQueue class instead of PriorityQueue.

Lets see list of constructors and methods in PriorityQueue class.


          Default constructor which orders the elements in natural ordering.

PriorityQueue(Collection<? extends E> c)
          PriorityQueue will be created containing the elements in the specified collection.
PriorityQueue(int initialCapacity)
 PriorityQueue will be created with the initial size specified and orders its elements according to their natural ordering.

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
 PriorityQueue will be created with the initial size specified and orders its elements according to the specified comparator

PriorityQueue(PriorityQueue<? extends E> c)
          PriorityQueue will be created with containing the elements in the specified priority queue.

PriorityQueue(SortedSet<? extends E> c)
          PriorityQueue will be created with containing the elements in the specified sorted set.


boolean add(E e) 
Inserts the Element into PriorityQueue.

void clear()
Removes all elements from PriorityQueue.

Comparator<? super E> comparator()
Return Comparator used to order the elements in queue, or returns null if its ordered the queue in natural ordering. 

boolean contains(Object o) 
Return true if particular Object present in the queue else false.

Iterator<E> iterator() 
Used to iterate over the elements in the queue.

boolean offer(E e) 
Its same as add() method inserts the Elements into PriorityQueue.

Element peek()
Retrieves the Element from the head of queue else return null if queue is empty.

Element poll()
Retrieves and removes the Element from the head of queue else return null if queue is empty.

boolean remove() 
Retrieves and removes head of this queue.

boolean remove(Object o) 
Removes given Object from the queue if its present in the queue.

int size()
Returns the queue size. 

Object[] toArray()
Returns Object array containing all of the elements in this queue.

 <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this queue; the run-time type of the returned array is that of the specified array and returned array elements are in no particular order.

Now lets see simple program using PriorityQueue class

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

public class PriorityQueueTest {

 public static void main(String[] args) {
  Queue<String> pq = new PriorityQueue<String>();
  System.out.println("\nPriorityQueue size() : "+pq.size());
  System.out.println("\nPriorityQueue peek() : "+pq.peek());
  System.out.println("\nIerating Queue Elements : ");
  Iterator<String> itr = pq.iterator();
  while (itr.hasNext()) {
   String string = (String);
   System.out.print(string+", ");
  System.out.println("\n\nPriorityQueue poll() : "+pq.poll());
  System.out.println("\nPriorityQueue size() : "+pq.size());
  System.out.println("\nPriorityQueue remove() : "+pq.remove());
  System.out.println("\nPriorityQueue remove(\".net\") : "+pq.remove(".net"));
  System.out.println("\nPriorityQueue contains() : "+pq.contains("java"));
  System.out.println("\nPriorityQueue toArray() : ");
  Object[] array = pq.toArray();
  for (Object object : array) {
   System.out.print(object.toString()+", ");


PriorityQueue size() : 6

PriorityQueue peek() : .net

Ierating Queue Elements : 
.net, c, Pascal, servlet, hibernate, java, 

PriorityQueue poll() : .net

PriorityQueue size() : 5

PriorityQueue remove() : Pascal

PriorityQueue remove(".net") : false

PriorityQueue contains() : true

PriorityQueue toArray() : 
c, hibernate, java, servlet,