PriorityQueue comparator() Method in Java

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.
Syntax:Â
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:Â
Â
Java
// Java code to illustrate comparator()import java.util.*;Â
public class Priority_Queue_Demo {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // Creating an empty Priority_Queue        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();Â
        // Adding elements to the queue        queue.add(20);        queue.add(24);        queue.add(30);        queue.add(35);        queue.add(45);        queue.add(50);Â
        System.out.println("Priority queue values are: " + queue);Â
        // Creating a comparator        Comparator comp = queue.comparator();Â
        // Displaying the comparator values        System.out.println("Since the Comparator value is: " + comp);        System.out.println("it follows natural ordering");    }} |
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.Â
Â
Java
// Java code to illustrate the use of comparator()import java.util.Comparator;import java.util.PriorityQueue;Â
class The_Comparator implements Comparator<String> {Â Â Â Â public int compare(String str1, String str2)Â Â Â Â {Â Â Â Â Â Â Â Â String first_Str;Â Â Â Â Â Â Â Â String second_Str;Â Â Â Â Â Â Â Â first_Str = str1;Â Â Â Â Â Â Â Â second_Str = str2;Â Â Â Â Â Â Â Â return second_Str.compareTo(first_Str);Â Â Â Â }}Â
public class Priority_Queue_Demo {    public static void main(String[] args)    {        PriorityQueue<String> queue = new        PriorityQueue<String>(new The_Comparator());Â
        queue.add("G");        queue.add("E");        queue.add("E");        queue.add("K");        queue.add("S");        queue.add("4");         Â
        System.out.println("The elements with the highest priority element at front of queue"                           + "order:");        while(!queue.isEmpty()){          System.out.print(" "+queue.poll());        }    }} |
The elements with the highest priority element at front of queueorder: S K G E E 4



