Java PriorityQueue Class Example

In Java, the PriorityQueue class is implemented as a priority heap. Heap is an important data structure in computer science. For a quick overview of heap, here is a very good tutorial.

1. Simple Example

The following examples shows the basic operations of PriorityQueue such as offer(), peek(), poll(), and size().

import java.util.Comparator;
import java.util.PriorityQueue;
 
public class PriorityQueueTest {
 
	static class PQsort implements Comparator<Integer> {
 
		public int compare(Integer one, Integer two) {
			return two - one;
		}
	}
 
	public static void main(String[] args) {
		int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
		PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();
 
		// use offer() method to add elements to the PriorityQueue pq1
		for (int x : ia) {
			pq1.offer(x);
		}
 
		System.out.println("pq1: " + pq1);
 
		PQsort pqs = new PQsort();
		PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs);
		// In this particular case, we can simply use Collections.reverseOrder()
		// instead of self-defined comparator
		for (int x : ia) {
			pq2.offer(x);
		}
 
		System.out.println("pq2: " + pq2);
 
		// print size
		System.out.println("size: " + pq2.size());
		// return highest priority element in the queue without removing it
		System.out.println("peek: " + pq2.peek());
		// print size
		System.out.println("size: " + pq2.size());
		// return highest priority element and removes it from the queue
		System.out.println("poll: " + pq2.poll());
		// print size
		System.out.println("size: " + pq2.size());
 
		System.out.print("pq2: " + pq2);
 
	}
}

Output:

pq1: [1, 3, 5, 8, 4, 7, 6, 10, 9]
pq2: [10, 9, 7, 8, 3, 5, 6, 1, 4]
size: 9
peek: 10
size: 9
poll: 10
size: 8
pq2: [9, 8, 7, 4, 3, 5, 6, 1]

2. Example of Solving Problems Using PriorityQueue

Merging k sorted list.

For more details about PriorityQueue, please go to doc.

Category >> Collections  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. deepu venkat on 2014-1-24

    Why do we use comparator?

  2. ryanlr on 2014-2-11

    From Java Doc –
    Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

  3. […] 堆(Heap)是一个基于树的数据结构,也可以称为优先队列( PriorityQueue),在队列中,调度程序反复提取队列中第一个作业并运行,因而实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。 […]

  4. […] time complexity of its operations are important (e.g., find-min, delete-min, insert, etc). In Java, PriorityQueue is important to […]

  5. vikrant on 2014-10-29

    another link on tech forum: http://www.writeulearn.com/priority-queue/

  6. […] 堆(Heap)是一个基于树的数据结构,也可以称为优先队列( PriorityQueue),在队列中,调度程序反复提取队列中第一个作业并运行,因而实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。 […]

  7. […] time complexity of its operations are important (e.g., find-min, delete-min, insert, etc). In Java, PriorityQueue is important to […]

  8. omi on 2015-2-23

    public int compare(Integer one, Integer two) {
    return two – one;
    }
    how this is reversing??what is the logic behind?

  9. ryanlr on 2015-2-23

    “Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.”

    (second-first) is equivalent to -(first-second). Consider the following node(ascending order), see if it helps.

    if (first == second)
    return 0;
    else if (first > second)
    return 1;
    else
    return -1;

  10. […] represented by a queue management system separate thread, its expertise in a method, its state by the website set of values of its properties and its behavior by the page method Run the thread. The agents have […]

  11. darpan shah on 2017-4-5

    In compare method what if variable one or two has negative value? In such cases this compare method wont result correctly. Instead it should be:
    public int compare(Integer one, Integer two) {
    return two.compareTo(one);
    }

    It always recommends to use compareTo method on every object while comparing.

Leave a comment

*