

Therefore, we have to use poll method to test the priority order of elements. Because if you simply iterate over a priority queue using an iterator or for-each loop, you may not get the priority order in which the queue will out the elements from it.
#Java queue how to
How to retrieve the elements in the order of their priority from priority queue The only difference is that poll method return null, whereas remove() throws exception if the queue is empty. Object poll() //retrieves and removes the head element Object remove() //retrieves and removes the head element There are two metods to fetch and remove head element of a queue. Whereas element() throws exception if the queue is empty Fetch and remove the head element of the queue The only difference between the two methods is that peek() returns null if the queue is empty. Object peek() //retrieves the head element of the queue

Object element() //retrieves the head element of the queue There are two methods using which we can retrieve head element of a queue. Head element of a queue is the first element of the queue that is out first from the queue. Poll method retrieves the head element of the queue and removes it. One more thing to notice here is that we have used poll() method inside while loop. In the output, we can see that elements have been displayed in the alphabetical order which is natural sorting order of String objects. Let’s see one example using default priority of String objects which is alphabetical. If we want to override the default priority, then we have to use comparision methods, such as Comparable or Comparator. How is priority decided?ĭefaultpPriority of elements is natural sorting order as per their data type. Therefore, he/she would stand in the queue before all others.

If a critical patient comes in, his/her priority to be seen by the doctor is higher than others. The higher priority element is placed before a lower priority element.Ī practical example of a priority queue would be a queue in a hospital. This orders its elements based on the priorities. The implementing class of Queue interface is PriorityQueue. Public interface Queue extends Collection PriorityQueue Class It means the element that goes first in a queue, comes out first and one that goes last, comes last. Queue is a data structure that maintains FIFO (First In First Out) order of elements.
