Wednesday, 5 September 2018

Max Priority Queue Implementation in Java

In this post, we will see how to implement max priority queue in Java.

Background:
Priority Queue is an non-blocking unbounded queue, the elements of which are arranged in either natural order (if no comparator is provided) or comparator provided as part of constructor. In both scenario, the queue is arranged in ascending order and the head of queue will have least value. Honestly, this does not make sense for Priority Queue to arrange elements in ascending order which can be called as Min Priority Queue

Have the elements arranged in reversed order will make it Max Priority Queue

Implementation:

Now the question arises, how can we make the Priority Queue as Max Priority Queue with the api provided by Java.
Here is the code example for Max Priority Queue in Java


package com.blogspot.tech693;

import java.util.Collections;
import java.util.PriorityQueue;

public class MaxPriorityQueue{

 public static void main(String[] args){
  // Generic Priority Queue -- Natural order
  PriorityQueue pq = new PriorityQueue<>(6);
  pq.add(4);
  pq.add(2);
  pq.add(1);
  pq.add(6);
  pq.add(5);
  
  System.out.println("Generic / Min Priority Queue::" + pq.poll());
  System.out.println("Generic / Min Priority Queue::" + pq.poll());
  
  // Max Priority Queue Example
  PriorityQueue pq1 = new PriorityQueue<>(6, Collections.reverseOrder());
  pq1.add(4);
  pq1.add(2);
  pq1.add(1);
  pq1.add(6);
  pq1.add(5);
  
  System.out.println("Max Priority Queue::" + pq1.poll());
  System.out.println("Max Priority Queue::" + pq1.poll());
 }
 
}



Output:

Generic / Min Priority Queue::1

Generic / Min Priority Queue::2

Max Priority Queue::6

Max Priority Queue::5


Explanation:
In the above code example, we tried to achieve Priority Queue in descending order. I strongly believe the head of the queue should be the highest element. By using Collections.reverseOrder() method we can conver the Priority Queue into Max Priority Queue.

That's all for Max Priority Queue Implementation in Java. If you have questions / suggestions, please mention in comments sections. Thanks. 

Related Articles:

You may also like:

No comments:

Post a comment