In this post, we will see about Java 8 PriorityQueue.
When the objects are supposed to be processed on the basis of their priority
, in that scenario we use PriorityQueue.
It’s a special type of queue
(also, unbound queues) where the elements can be ordered either as per their natural ordering or based on a custom comparator implemented at the time of declaration.
Table of Contents
Suppose two-person went to two different banks to deposit some money, Person A
is serviced on the basis of the queue formed on the cash counter, Person B
is serviced according to the token numbers provided by the bank (Underlying Queue), now here both follows FIFO
(First in First Out) model, but their priorities are determined by different factors, for Person A
it’s their arrival time (standing in a queue), but for Person B
it’s just the token number (smaller number serviced first). Now, even here we can modify our system, that senior citizens are serviced first, so this is kind of a system where we have set few priorities (maybe on the basis of age).
Priority Queue Data Structure
Let’s say you want to read few books and prioritize it based on number of pages. You would like to read thinner books first and gradually move to thicker books.
In the given example, the front of the priority queue contains the smallest element, as per the specified ordering, and the rear contains the greatest element. Since the element is removed from the front, therefore the least element is removed first.
Some Important Points
- Non-comparable objects cannot be implemented using Priority Queue.
- Null is not allowed, as we can’t compare it with any value.
- The basic retrieval operations like, poll(), remove(), peek() access the element at the front or at the head of the queue.
Constructors
- PriorityQueue(): Creating a Priority Queue with default initial capacity and following the natural ordering for its elements.
- PriorityQueue(Collection<E> c): It creates Priority Queue containing elements in the collection specified in the argument.
- PriorityQueue(int initialCapacity): It is similar to the PriorityQueue() with the specified initial capacity.
- PriorityQueue(int initialCapacity, Comparator<E> comparator): It is similar to PriorityQueue(int initialCapacity), but the extra parameter specifies the order of its element, which should be according to the specified comparator.
Methods
- boolean add(element) : This method will insert the element into this priority queue.
- boolean remove(element) : This method will remove one occurrence of element from the queue.
- poll() : This method returns the element at the head of the queue and hence removes it from the queue, else returns NULL (if the given queue is empty).
- peek() : This method is same as poll(), the only difference is, it does not remove the head after returning it.
- boolean contains(element) : It returns true if the given queue contains the specified element in it.
- clear() :This method will remove all the elements from a Priority Queue, that is it will empty an existing Priority Queue and does not delete it.
- boolean offer(element) : This method acts as add() method, as it is also used to insert a particular element into the Priority Queue.
- int size() : This method will return the number of elements in the priority queue.
- toArray() : This method return type is array, it returns all the elements of the priority queue in an array.
- Comparator comparator() : This method will return the comparator which is used to order the elements of the priority queue, and returns NULL value if the queue follows natural ordering.
1 2 3 |
pQueue.add(“Java”) ; // adding “Java” to string type priority queue pQueue |
1 2 3 |
pQueue.remove(“Java”) ; // remove “Java” from string type priority queue pQueue |
1 2 3 |
pQueue.poll(); // if pQueue is the Priority queue given in the diagram above then it will return 50 and remove from the Priority Queue |
1 2 3 |
pQueue.peek() ; // if pQueue is the Priority queue given in the diagram above then it will return 50. |
1 2 3 4 5 |
pQueue.contains(250) ; // if pQueue is the Priority queue given in the diagram above then it will return true. pQueue.contains(365) ; // if pQueue is the Priority queue given in the diagram above then it will return false. |
1 2 3 |
pQueue.clear() ; // if we try to print the queue after invoking this function, it will return [] |
1 2 3 |
pQueue.offer(25) ; // will add 25 to the pQueue according to its natural ordering, |
1 2 3 |
pQueue.size() ; // if pQueue is the Priority queue given in the diagram above then it will return 5. |
1 2 3 |
Object[] arr1 = pQueue.toArray() ; // this will store all the elements of the priority queue pQueue in an array arr1, therefore we can traverse the elements using simple array traversal |
1 2 3 |
pQueue.comparator() ; // if pQueue is the Priority queue given in the diagram above then it will return NULL, because it follows natural ordering. |
Creating a PriorityQueue
Now, since we have discussed all the basic operations, methods and constructors of the Priority Queue Class, let’s see how to implement them in different ways,
Since, for integer type it is easy to differentiate, let’s implement for string type.
We will see how priorities will change the sequence for some of the best-selling books
Using No-arg constructor (Natural ordering)
In this program, we created a PriorityQueue of string type with no comparator, so it will use the natural ordering, which would according to the Dictionary (Alphabetically), added few string values to understand the working.
We can also see the application of add() and remove() here.
Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog.Java2blogPrograms; import java.util.PriorityQueue; import java.util.PriorityQueue; public class PriorityQueueMain { public static void main (String[] args) { // Creating a Priority Queue of String Type PriorityQueue<String> pQueue = new PriorityQueue<>() ; // Adding the items to a Priority Queue (ENQUEUE) using add() pQueue.add("Don Quixote") ; pQueue.add("The Master and Margarita") ; pQueue.add("The Hobbit") ; pQueue.add("Dream of the Red Chamber") ; pQueue.add("A Tale of Two Cities") ; pQueue.add("And Then There Were None") ; // Removing and printing items from the Priority Queue (DEQUEUE) using remove() while (!pQueue.isEmpty()) { System.out.println(pQueue.remove()) ; } } } |
Output:
And Then There Were None
Don Quixote
Dream of the Red Chamber
The Hobbit
The Master and Margarita
Using Custom Comparator
In this program, we have implemented the PriorityQueue with a custom comparator specified separately using its proper syntax, here we can see how we have prioritized according to the number of books.
Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package org.arpit.java2blog.Java2blogPrograms; import java.util.Comparator; import java.util.PriorityQueue; class Book { String bookName; int pages; public Book(String name, int pages) { this.bookName = name; this.pages = pages; } @Override public String toString() { return "Book name is : " + bookName + " and number of pages are :" + pages; } } class byPages implements Comparator<Book> { @Override public int compare(Book st1, Book st2) { return st2.pages - st1.pages; } } public class PriorityQueueMainComparator { public static void main(String[] args) { byPages comp = new byPages(); // Adding elements in pQueue using offer, we can also use add() PriorityQueue<Book> pQueue = new PriorityQueue<Book>(10, comp); pQueue.offer(new Book("A Tale of Two Cities", 322)); pQueue.offer(new Book("The Master and Margarita", 444)); pQueue.offer(new Book("Don Quixote", 246)); pQueue.offer(new Book("And Then There Were None", 342)); pQueue.offer(new Book("Think and Grow Rich", 401)); pQueue.offer(new Book("The Hobbit", 276)); pQueue.offer(new Book("Dream of the Red Chamber", 378)); // Removing the head elements using poll to print in order according to the // implemented comparator System.out.println(pQueue.poll()); System.out.println(pQueue.poll()); System.out.println(pQueue.poll()); System.out.println(pQueue.poll()); System.out.println(pQueue.poll()); System.out.println(pQueue.poll()); System.out.println(pQueue.poll()); } } |
Here, is the output for the code, where it is clearly seen that the elements are according to the number of pages of the book.
Output :
Book name is : Think and Grow Rich and number of pages are :401
Book name is : Dream of the Red Chamber and number of pages are :378
Book name is : And Then There Were None and number of pages are :342
Book name is : A Tale of Two Cities and number of pages are :322
Book name is : The Hobbit and number of pages are :276
Book name is : Don Quixote and number of pages are :246
That’s all about Priority Queue in java 8.