Priority Queue Data Structure

Priority queue data structure in java is an implementation of queue interface.

Unlike other queue implementation classes(Like linkedlist) , priority queue does not orders elements based on insertion order (first in first out) but instead orders the elements according to their priorities. Element with the least priority is the head of the queue and is always removed first. Element with highest priority is always removed last.

Priority of the element is decided based on their natural ordering or using a comparator if provided in the constructor while creating the priority queue. In case no comparator is specified in the constructor, priority queue orders the elements based on their natural ordering.

  • Head is always the element with least priority.
  • Priority queue does not allow insertion of null element.
  • To insert objects of user defined class, priority queue expects the objects to belong to a class implementing comparable interface.
  • Priority queue does not allow insertion of non-comparable objects. This is because to decide the priority of any element which is inserted it has to be compared with existing elements in the queue.

Example : Priority Queue Data Structure

1.) creating priority queue

PriorityQueue<String> pq = new PriorityQueue<String>();
// Add elements to piority queue
pq.add("Marie");
pq.add("Jasmine");
pq.add("Rose");

System.out.println("priority queue : " + pq);
            

OUTPUT

priority queue: [Jasmine, Marie, Rose]
            

2.) remove elements from priority queue

System.out.println("priority queue: " + pq);

// check head element of the queue
String head = pq.peek();
System.out.println("head of the queue:" + head);

// remove element from the queue
pq.poll();
System.out.println("queue after removing an element: " + pq);
            

OUTPUT

priority queue: [Jasmine, Marie, Rose]
head of the queue: Jasmine
queue after removing an element: [Marie, Rose]
            

Summary

In this article we learnt about the Priority Queue Data Structure using Java. For better understanding we looked into some code snippets of queues add, peek & poll operations.
Hope you liked the article !


Leave a Comment