

Here is our sample program to demonstrate how to use PriorityQueue in Java. One of the best book which extensively covers this topic and explains about almost all the collection classes available in Java till Java SE 6. Good knowledge of the Java Collection framework is absolutely necessary to become an expert Java developer and if you want to become one, I suggest you read Java Generics and Collection by Maurice Naftalin. It provides constant-time access to the highest or lowest priority element. So, if you want to process elements in their relative priority order, you can use PriorityQueue in Java. Once this element is removed from the root, the next maximum/minimum is promoted to root.

In this data structure root of the binary tree always contain either maximum value (max heap) or minimum value (min heap), since you have constant time access to root, you can get max or minimum value in constant time. priority queue data structure is internally implemented using a binary heap data structure, which allows constant time access to the maximum and minimum element in a heap by implementing max heap and min heap data structure.

When you add or remove elements from PriorityQueue, other elements are compared to each other to put the highest/lowest priority element at the head of the queue. Like other collection classes which provide sorting, PriorityQueue also uses Comparable and Comparator interface for priority. So when you call remove() or poll() method, you will get this element, and next on priority will acquire the head spot. The only guaranteed PriorityQueue gives is that the lowest or highest priority element will be at the head of the queue. TreeSet or TreeMap, which also allows you to iterate over all elements, in the priority queue, there is no guarantee on iteration. Though it provides sorting, it's a little different from other Sorted collections e.g. This class implements the Queue interface and provides a sorted element from the head of the queue. PriorityQueue is another data structure from the Java Collection framework, added in Java SE 5.
