The Wayback Machine - https://web.archive.org/web/20240624062621/https://www.geeksforgeeks.org/implement-priorityqueue-comparator-java/
Open In App

Implement PriorityQueue through Comparator in Java

Last Updated : 05 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite : Priority Queue, Comparator Priority Queue is like a regular queue, but each element has a “priority” associated with it. In a priority queue, an element with high priority is served before an element with low priority. For this, it uses a comparison function which imposes a total ordering of the elements. 

The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used Constructors : 

  • public PriorityQueue() : This creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
  • public PriorityQueue(Collection c) : This creates a PriorityQueue containing the elements in the specified collection(c). If the specified collection is an instance of a SortedSet, this priority queue will be ordered according to the same ordering, else this priority queue will be ordered according to the natural ordering of its elements.
  • public PriorityQueue(int capacity, Comparator comparator) : This creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
Parameters:
capacity - the initial capacity for this priority queue
comparator - the comparator that will be used to order this priority queue. 
If null, the natural ordering of the elements will be used.
  • public PriorityQueue(SortedSet ss) : Creates a PriorityQueue containing the elements in the specified sorted set. This priority queue will be ordered according to the same ordering as the given sorted set.

Sample code provided illustrates students with high priority(based on cgpa) are served before the students having low cgpa. 

Implementation:

Java




// Java program to demonstrate working of
// comparator based priority queue constructor
import java.util.*;
 
public class Example {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        // Creating Priority queue constructor having
        // initial capacity=5 and a StudentComparator instance
        // as its parameters
        PriorityQueue<Student> pq = new
             PriorityQueue<Student>(5, new StudentComparator());
                 
                // Invoking a parameterized Student constructor with
                // name and cgpa as the elements of queue
                Student student1 = new Student("Nandini", 3.2);
                 
                // Adding a student object containing fields
                // name and cgpa to priority queue
                pq.add(student1);
                Student student2 = new Student("Anmol", 3.6);
                        pq.add(student2);        
                Student student3 = new Student("Palak", 4.0);
                        pq.add(student3);
                 
                // Printing names of students in priority order,poll()
                // method is used to access the head element of queue
                System.out.println("Students served in their priority order");
                 
                while (!pq.isEmpty()) {
                System.out.println(pq.poll().getName());
        }
    }
}
 
class StudentComparator implements Comparator<Student>{
             
            // Overriding compare()method of Comparator
                        // for descending order of cgpa
            public int compare(Student s1, Student s2) {
                if (s1.cgpa < s2.cgpa)
                    return 1;
                else if (s1.cgpa > s2.cgpa)
                    return -1;
                                return 0;
                }
        }
 
class Student {
    public String name;
    public double cgpa;
         
    // A parameterized student constructor
    public Student(String name, double cgpa) {
     
        this.name = name;
        this.cgpa = cgpa;
    }
     
    public String getName() {
        return name;
    }
}


Output:

Students served in their priority order
Palak
Anmol
Nandini

Note : This type of Priority queue is preferred in scenarios where customized ordering is required, i.e when one wants a different sorting order, then one can define its own way of comparing instances. Comparator can be implemented if there is a more complex comparing algorithm, e.g. multiple fields and so on.



Similar Reads

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: Th
2 min read
How to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java?
A PriorityQueue is a data structure that allows elements to be processed based on their priority. By default, it orders elements according to their natural ordering (e.g., numeric values in ascending order). However, sometimes we need a different sorting order based on specific criteria. In this article, we will learn to Customize the Ordering of E
4 min read
Custom Comparator for a Specific Element type in a PriorityQueue in Java
PriorityQueue in Java is a data structure that stores elements according to their specified natural order or comparison. By default, it uses a natural order, but we can also define customized comparisons to sort things out based on specific criteria. Custom Comparator in PriorityQueueA Custom Comparator in Java is an interface that defines a method
3 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Java | Collectors maxBy(Comparator comparator) with Examples
Collectors maxBy(Comparator&lt;? super T&gt; comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the maximal element according to a given Comparator, described as an Optional&lt;T&gt;. Syntax: public static &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt; maxBy(Comparato
3 min read
Java | Collectors minBy(Comparator comparator) with Examples
Collectors minBy(Comparator&lt;? super T&gt; comparator) is used to find an element according to the comparator passed as the parameter. It returns a Collector that produces the minimal element according to a given Comparator, described as an Optional&lt;T&gt;. Syntax: public static &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt; minBy(Comparato
4 min read
Java Program to Implement PriorityQueue API
A PriorityQueue is a linear data structure in which the elements are ordered according to their natural ordering or by some custom comparator provided at the queue at construction time. In PriorityQueue, the front of the queue points to the least element, and the rear points to the greatest element according to the natural Ordering. For alphabetica
4 min read
How to Use a PriorityQueue to Implement a Priority-Based Task Scheduler in Java?
In Java, the PriorityQueue data structure offers an efficient way to manage tasks based on their assigned priorities. Elements with higher priority are dequeued before elements with lower priority. It uses a heap data structure internally to maintain the ordering of elements. In this article, we will learn how to use a PriorityQueue to implement a
4 min read
How to Implement a Custom Comparator for a LinkedHashSet in Java?
In Java, we cannot directly implement a custom comparator for a LinkedHashSet. But sometimes we need a requirement of custom comparator for example custom sorting. So, we can use some alternative approaches to fulfill the requirements. In this article, we will be using a class for creating the custom comparator and this class will implement the Com
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
three90RightbarBannerImg