PriorityBlockingQueue comparator() method in Java (original) (raw)

Last Updated : 03 Apr, 2023

The comparator() method of PriorityBlockingQueue returns the comparator that can be used to order the elements in a PriorityBlockingQueue. The method returns null value if the queue follows the natural ordering pattern of the elements. Syntax:

public Comparator<? super E> comparator()

Returns: This method returns the comparator set used to order the elements of the set in a specific order. It returns a null value if the PriorityBlockingQueue follows the default or natural ordering pattern. Below programs illustrate comparator() method of PriorityBlockingQueue: Example 1: To demonstrate comparator() method on PriorityBlockingQueue which contains a list of integers.

Java

import java.util.concurrent.PriorityBlockingQueue;

import java.util.*;

public class GFG {

`` public static void main(String[] args)

`` throws InterruptedException

`` {

`` PriorityBlockingQueue<Integer> PrioQueue

`` = new PriorityBlockingQueue<Integer>();

`` PrioQueue.put( 45815616 );

`` PrioQueue.put( 4981561 );

`` PrioQueue.put( 4594591 );

`` PrioQueue.put( 9459156 );

`` String str = PrioQueue.toString();

`` Comparator comp = PrioQueue.comparator();

`` System.out.println("Comparator value: " + comp);

`` if (comp == null )

`` System.out.println("PriorityBlockingQueue"

`` + "follows natural ordering");

`` else

`` System.out.println("PriorityBlockingQueue follows"

`` + comp);

`` }

}

Output:

Comparator value: null PriorityBlockingQueuefollows natural ordering

Example 2: To demonstrate comparator() method on PriorityBlockingQueue which contains a list of integers.

Java

import java.util.concurrent.PriorityBlockingQueue;

import java.util.*;

class COMPARING implements Comparator<String> {

`` public int compare(String str1, String str2)

`` {

`` return str2.compareTo(str1);

`` }

}

public class GFG {

`` public static void main(String[] args)

`` throws InterruptedException

`` {

`` int capacityOfQueue = 5 ;

`` PriorityBlockingQueue<String> characters

`` = new PriorityBlockingQueue<String>(capacityOfQueue,

`` new COMPARING());

`` characters.add("Geeks");

`` characters.add("forGeeks");

`` characters.add("A computer portal");

`` Comparator comp = characters.comparator();

`` System.out.println("Comparator value is: " + comp);

`` if (comp == null )

`` System.out.println("PriorityBlockingQueue"

`` + "follows natural ordering");

`` else

`` System.out.println("PriorityBlockingQueue follows: "

`` + comp);

`` System.out.println("\nThe elements after custom Comparator");

`` for (String e : characters)

`` System.out.print(e + ", ");

`` }

}

Output:

Comparator value is: COMPARING@28d93b30 PriorityBlockingQueue follows: COMPARING@28d93b30

The elements after custom Comparator forGeeks, Geeks, A computer portal,

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#comparator–