
(priorityQueue.peek()) //Michael Insertion Now, the head of the queue would have Michael. The first dequeue returned Adam, and the second returned Kevin. Remember that the remove() method is stricter as it throws an exception if the queue is empty. We have used the remove() and the poll() method. Let us remove two elements from the queue. These print Adam because it is the first element in the queue (head of the queue). Remember that the element() throws an NoSuchElementException if the queue is empty. The peek() or the element() method retrieves the head of the queue without removing it. We will explore the methods or operations that we can do on a Priority Queue in Java. The elements would be ordered lexicographically as, Adam -> Kevin -> Michael -> Mitch -> Weiss -> Will
PRIORITY QUEUE IMPLEMENTATION IN JAVA CODE
The above code creates a PriorityQueue and adds a few names into it. PriorityQueue priorityQueue = new PriorityQueue() A String has a natural ordering because it implements Comparator. We will create a Priority Queue consisting of String objects. Let us look at examples for each of these. Note that when we pass a custom comparator, it overrides the natural ordering of the elements. Each of these comes in two flavours: one throws an exception if the operation fails, while the other returns a special value (either null or false). Queue methodsĪ Queue is a collection but provides additional methods for insertion, extraction and inspection.

Since a Priority Queue is a Queue, I will briefly summarize the operations that can be performed on a Queue. In this post, we will learn about the Priority Queue in Java, its methods, and its application.

The elements of the Priority Queue are ordered according to their natural ordering (when the object implements the Comparable interface), or by a Comparator provided during the priority queue construction time. A Practical Application Example for Priority Based ProcessingĪ Priority Queue in Java is an unbounded Queue based on a priority heap.Time complexity of the Priority Queue methods.Iterator and toArray methods do not obey the queue ordering.Passing an initial capacity for the priority queue.Creating a PriorityQueue from a PriorityQueue.Creating a PriorityQueue from a SortedSet.Specifying a Comparator overrides the natural ordering.

Priority Queue – Specifying a Comparator for ordering.
