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.
comp_set = (PriorityQueue)Priority_Queue.comparator()
Parameters: The method does not take any parameters.
Return Value: The method returns the comparator used to order the elements of the queue in a specific order. It returns a Null value if the queue follows the default or natural ordering pattern.
Below programs illustrate the java.util.PriorityQueue.comparator() method:
Program 1: When using natural ordering of the elements:
Priority queue values are: [20, 24, 30, 35, 45, 50] Since the Comparator value is: null it follows natural ordering
Program 2: When using a specific comparator.
The elements with the highest priority element at front of queueorder: S K G E E 4
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.