A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
where E is the type of elements held in this queue
Types of PriorityQueue
- Max Priority Queue
- Min Priority Queue
Example of Default Priority Queue
5 5 10
In Java, Priority Queue, by default implement min Priority Queue, If we need to change the order of Priority Queue from min to max Priority Queue, then we use some methods as follows:
- Using default Comparator Collections.reverseOrder()
- Using custom Comparator
- Using lambda expression
Method 1: Using default Comparator Collections.reverseOrder()
20 20 15
Method 2: Using custom Comparator
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.
20 20 15
Method 3: Using lambda expression
Lambda expression since Java 8 has come to use, lambda function names its input parameters a and b and returns (b-a), which is basically what the int comparator class does except it returns a-b.
20 20 15
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.