Java Utility Library

Java PriorityQueue - comparator() Method



The java.util.PriorityQueue.comparator() method returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements.

Syntax

public Comparator<? super E> comparator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the comparator used to order this queue, or null if this queue is sorted according to the natural ordering of its elements.

Exception

NA.

Example:

In the example below, the java.util.PriorityQueue.comparator() method returns the comparator which returns null as the given queue is already sorted according to the natural ordering system.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a priority queue
    PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>();

    //populating the priority queue
    PQueue.add(30);
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(100);
    PQueue.add(-10);

    //printing the priority queue
    System.out.println("PQueue contains: " + PQueue); 

    //creating comparator
    Comparator comp = PQueue.comparator();
    
    //printing comparator value
    System.out.println("Comparator value is: "+ comp);  
  }
}

The output of the above code will be:

PQueue contains: [-10, 10, 20, 100, 30]
Comparator value is: null

❮ Java.util - PriorityQueue