Implement PriorityQueue through Comparator in Java
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
- 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.
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.