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 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.
Queue before using the comparator: [S, K, E, E, G, 4] The elements sorted in descendingorder: S K E E G 4
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Implement PriorityQueue through Comparator in Java
- Stream sorted (Comparator comparator) method in Java
- Java | Collectors maxBy(Comparator comparator) with Examples
- Java | Collectors minBy(Comparator comparator) with Examples
- PriorityQueue add() Method in Java
- PriorityQueue contains() Method in Java
- PriorityBlockingQueue comparator() method in Java
- TreeSet comparator() Method in Java
- PriorityQueue spliterator() method in Java
- PriorityQueue peek() Method in Java
- PriorityQueue offer() Method in Java
- PriorityQueue poll() Method in Java
- PriorityQueue toArray() Method in Java
- PriorityQueue clear() Method in Java
- PriorityQueue size() Method in Java
- PriorityQueue remove() Method in Java
- PriorityQueue iterator() Method in Java
- ConcurrentSkipListSet comparator() method in Java with Examples
- Comparator thenComparingInt() method in Java with examples
- Comparator thenComparingLong() method in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.