Priority Queue in Java

Shubham Dadasaheb Sawant
3 min readJan 22, 2022

--

We all know Regular Queue that is First In First Out data structure. Where the element that goes first comes out first. Now we’ll talk about Priority Queue.

Basically in Queue the data is stored in the queue the way it enters. But priority queue stores the data by default in ascending order. As shown below the first element at front end is the least element and the element at the rear side is the largest element among inserted into the Priority Queue.

The implementation code for above as follows:

In code even if you add elements in any order, the elements in priority queue by default will be inserted in ascending order ie from form front side( least element) to rear side (largest element);

In the same way if u want to insert element in descending order ie at front side( largest element) and at rear side( least element ) you can do the same by using comparator.

Or the above output can be achieved by implementing Comparator interface to your TestCompar class and later using the object of this class in Priority Queue declaration.

In the same way for the string strings which stores elements in ASCII order the least ASCII will be at front side and higher ASCII will be at rear side. For example

Famous Interview Question on priority Queue

Suppose you have organization and you have multiple employees with given data as their name and salary. By using concept of Priority Queue and comparator write 2 programs for displaying least salary employee and highest salary employee with their respective names .

  1. For displaying Employee with least salary amount.

2. For displaying Employee with least salary amount.

--

--

Shubham Dadasaheb Sawant
Shubham Dadasaheb Sawant

No responses yet