PriorityQueue

java.util.PriorityQueue Example

Photo of Chandan SinghChandan SinghDecember 19th, 2014Last Updated: December 20th, 2014
0 141 2 minutes read

In this example, we shall demonstrate how to use thejava.util.PriorityQueue Class. ThePriorityQueue Class implements the contract defined through theQueue interface. ThePriorityQueue is like other collections as in, it is unbounded and we can specify the starting size. Also, it is not threadsafe in a multi-threaded environment.PriorityQueue Class was introduced since Java 5.
 
 
 
 
 
 

TIP:
For multi-threaded environment, consider using thePriorityBlockingQueue class.

PriorityQueue Class sorts the tasks assigned to it using either the natural order(i.e. by implementingComparable) or by the custom definedComparator Object.

PriorityQueue(int initialCapacity, Comparator comparator) constructor accepts an object ofComparator Class to sort the tasks.

NOTE:
Before offering elements to a sorted collection likePriorityQueue, confirm if the element isnot null.Null elements cannot be sorted and hence, an uglyNullPointerException is thrown.

Let’s take a look at how thePriorityQueue Class works and how it can be used.

Request.java:

package com.javacodegeeks.examples.bean;public class Request implements Comparable<Request>{private String requestName = "";private int priorityStatus = 0;/** * @param requestName * @param priorityStatus */    public Request(String requestName, int priorityStatus)    {    this.requestName = requestName;    this.priorityStatus = priorityStatus;    }            @Override    public int compareTo(Request otherRequest)    {    return Integer.compare(priorityStatus, otherRequest.priorityStatus);    }@Override    public String toString()    {    return "Request [requestName= " + requestName + ", priorityStatus=" + priorityStatus + "]";    }}

PriorityQueueExample.java:

package com.javacodegeeks.examples.concurrent;import java.util.PriorityQueue;import com.javacodegeeks.examples.bean.Request;/** * @author Chandan Singh */public class PriorityQueueExample{public static void main(String[] args)    {    PriorityQueue<Request> queueExample = new PriorityQueue<>();    queueExample.offer(new Request("ABC", 2));    queueExample.offer(new Request("ABC", 5));    queueExample.offer(new Request("ABC", 1));    while(!queueExample.isEmpty())    System.out.println(queueExample.poll());//remove and print the top element           }}

OUTPUT:

Request [requestName= ABC, priorityStatus=1]Request [requestName= ABC, priorityStatus=2]Request [requestName= ABC, priorityStatus=5]

The generic class being put inPriorityQueue Object must have implemented eithercomparators or providecomparables objects toPriorityQueue. Failing to provide this(sorting mechanism) may lead toClassCastException. Care should be taken while designing thecomparators andcomparables to avoidsilent integer overflows, which may lead the program to exhibit non-deterministic behaviour. In case of ties for priority, the tasks are arbitrarily chosen.

We can also add other collection objects to the queue using thePriorityQueue(Collection c) constructor.

  • Apart, from the methods used in the example above thePriorityQueue Class offers a number of other utility methods, too.
    E peek() : Returns the head of the queue but does not remove it likePoll() method.
  • Comparator comparator() : Returns the comparator used by thePriorityQueue.
  • Object toArray() : Returns the array of all tasks enqueued.
  • int size() : Returns the number of elements enqueued inPriorityQueue.
  • boolean contains(Object e) : Returnstrue if the object is enqueued.
  • boolean remove(Object e) : Returnstrue and removes a single instance of thetask passed as argument.False, otherwise.
  • void clear() Removes all the tasks enqueued.

Time Complexity :

Queueing & Removing from Queue :O(log n). (e.g.offer(),poll())
Searching :O(n)(e.g.contains())
Access :O(1)(e.g.size(), peek())

Conclusion :

Here, we tried to understand the use ofPriorityQueue Class and how we can use the same when we have tasks that need to be executed in priority basis.

Download
You can download the source code of this example here:PriorityQueueExample.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Chandan SinghChandan SinghDecember 19th, 2014Last Updated: December 20th, 2014
0 141 2 minutes read
Photo of Chandan Singh

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.