The Java util package has a queue interface that defines the queue interface which has methods defined for methods in a queue. The general implementation of a queue is a first-in-first-out ordering of elements. The interface has many methods we are focusing on two
poll() – Retrieves and removes the head of this queue, or returns null if this queue is empty.
offer(element e) – Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
The queue interface has many implementations. For special ordering within the queue, java introduces an implementation class Priority_Queue to allow ordering within the queue to be of a special type.
An unbounded priority queue based on a priority heap. 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. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit the insertion of non-comparable objects (doing so may result in ClassCastException).
Sorting elements using a Priority Queue
Let’s walk through some code examples of how a priority queue can be used to order elements in ascending or descending order.
1. Sorting elements in ascending order in the priority queue
A comparator class allows us to define how elements are ordered in the queue. To sort the elements in ascending order we need to define the queue as below. (The comparator has been written in an expanded form for simplicity.)
2. Sorting elements in descending order in the priority queue
A comparator class allows us to define how elements are ordered in the queue. To sort the elements in descending order we need to define the queue as below. (The comparator has been written in an expanded form for simplicity).
Please Login to comment...