Wednesday 5 September 2018

Max Priority Queue Implementation in Java

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

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


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);
  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());
  System.out.println("Max Priority Queue::" + pq1.poll());
  System.out.println("Max Priority Queue::" + pq1.poll());


Generic / Min Priority Queue::1

Generic / Min Priority Queue::2

Max Priority Queue::6

Max Priority Queue::5

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