How to use Java PriorityQueue with Examples
Tags: java, priorityqueue, example
Published: 2021-03-05 15:47:55

https://grokonez.com/java/how-to-use-java-priorityqueue-with-examples

[no_toc]In the tutorial, Grokonez introduces how to work with Java PriorityQueue by examples: 
<ul>
<li>How does Java PriorityQueue work?</li>
<li>Explore Java PriorityQueue Hierarchy</li>
<li>Create Java PriorityQueue with Integer, String, and Custom Object Class</li>
</ul>

Related posts:
- <a href="https://grokonez.com/java/how-to-use-java-treemap-with-examples">Java TreeMap with Examples</a>

<!--more-->
<h2 id="java-priority-queue">Java PriorityQueue</h2>
- Java PriorityQueue is an unbounded priority queue.
- The elements of the priority queue are ordered according to their natural ordering, or by a Comparator.
<ul>
<li>The front of the priority queue contains the least element.</li>
<li>And the rear of the priority queue contains the greatest element.</li>
</ul>


<img src="https://grokonez.com/wp-content/uploads/2019/05/grokonez-howto-java-priority-queue-examples.png" alt="grokonez-howto-java-priority-queue-examples" width="750" height="377" class="alignnone size-full wp-image-17893" />

- PriorityQueue does not permit <code>null</code> elements. 
- PriorityQueue does not permit insertion of non-comparable objects. <code>ClassCastException</code> will be throwed.
- The head of this queue is the least element. The queue operations <code>poll</code>, <code>remove</code>, <code>peek</code>, and element access the element at the head of the queue.
- Java PriorityQueue is not synchronized. Multiple threads should not access the same PriorityQueue concurrently if having any of the threads modifies the queue.
<h3>Java PriorityQueue Hierarchy</h3>

<img src="https://grokonez.com/wp-content/uploads/2019/05/grokonez-java-priority-queue-hierarchy-examples.png" alt="grokonez-java-priority-queue-hierarchy-examples" width="454" height="514" class="alignnone size-full wp-image-17894" />
<h2 id="java-priority-queue-with-integer-example">Java PriorityQueue with Integer Example</h2>
In the follwing example, We create an Integer Java PriorityQueue, then do a list operations on the queue:
<ul>
<li>Insert an element to PriorityQueue with <code>offer</code> and <code>add</code> method.</li>
<li>Retrieve a head value of the Queue, but NOT remove it by <code>peek()</code> method.</li>
<li>Removes a single instance of the specified element from this queue by <code>remove(Object o)</code> method.</li>
<li>Retrieves and removes the head of this queue by <code>poll()</code> method.</li>
</ul>

Example:

<pre><code class="language-java">
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue<Integer> intQueue = new PriorityQueue<Integer>();
		// Inserts the specified element into this priority queue.
		intQueue.offer(10);
		intQueue.offer(1);
		intQueue.offer(5);
		intQueue.offer(9);
		
		// E poll(): Retrieves and removes the head of this queue
		System.out.println(intQueue.remove());
		/*
		 * 1
		 */
		
		// Retrieves, but does not remove, the head of this queue
		int head = intQueue.peek();
		System.out.println("headValue = " + head); // headValue = 5
		
		// Inserts the specified element into this priority queue.
		intQueue.add(7);
		intQueue.add(2);
		
		head = intQueue.element();
		System.out.println("headValue = " + head); // headValue = 2
		
		// Removes a single instance of the specified element from this queue, if it is present.
		boolean containOrNot = intQueue.remove(9);
		System.out.println(containOrNot); // true
		
		System.out.println("---");
		
		while(!intQueue.isEmpty()) {
			System.out.println(intQueue.poll());
		}
		
		/*
		 * 2
		 * 5
		 * 7
		 * 10
		 */
	}
}</code></pre>

- In above example, we use <code>PriorityQueue()</code> Constructor to create a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

- <code>add()</code> and <code>offer()</code> method, both can insert an element to a PriorityQueue, But what is the difference?
+ The <code>offer</code> method inserts an element if possible, otherwise returning <code>false</code>. 
+ This differs from the <code>Collection.add</code> method, which can fail to add an element only by throwing an unchecked exception. 

- The <code>remove()</code> and <code>poll()</code> methods remove and return the head of the queue. 
-> BUT when the queue is empty, the <code>remove()</code> method throws an exception, while the <code>poll()</code> method returns null.

- The <code>element()</code> and <code>peek()</code> retrive the head's value of the queue and NOT remove. When the queue is empty:
+ <code>element()</code> throws <code>NoSuchElementException</code>.
+ <code>peek()</code> returns <code>null</code>.

Now we do an example to iterate all elements of a Java PriorityQueue:

- using <code>iterator()</code>: to return an iterator over the elements in the queue.
- using <code>toArray()</code>: to return an array containing all the elements in the queue.

<pre><code class="language-java">
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples{

	public static void main(String[] args) {
		Queue&lt;Integer&gt; intQueue = new PriorityQueue&lt;Integer&gt;();
		// Inserts the specified element into this priority queue.
		intQueue.offer(10);
		intQueue.offer(1);
		intQueue.offer(5);
		intQueue.offer(9);
		
		// Returns an iterator over the elements in this queue.
		Iterator&lt;Integer&gt; intIterator = intQueue.iterator();
		
		while (intIterator.hasNext()) 
            System.out.print(intIterator.next() + &quot; &quot;);
		/*
		 * 1 9 5 10 
		 */
		
		System.out.println();
		
		// Returns an array containing all of the elements in this queue.
		Object[] intArr =  intQueue.toArray();
		for(int i=0; i&lt;intArr.length; i++) {
			System.out.print(intArr[i] + &quot; &quot;);
		}
		/*
		 * 1 9 5 10 
		 */
	}
}</code></pre>
<h2 id="java-priority-queue-with-string-example">Java PriorityQueue with String Example</h2>
- Example: Create Java String PriorityQueue using Natural Ordering of String

<pre><code class="language-java">
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue<String> strQueue = new PriorityQueue<String>();
		
		// Inserts the specified element into this priority queue.
		strQueue.offer("Jack");
		strQueue.offer("Charlie");
		strQueue.offer("Joe");
		strQueue.offer("George");
		
		while(!strQueue.isEmpty()) {
			System.out.print(strQueue.poll() + " ");
		}
		
		/*
		 * -> Charlie George Jack Joe   
		 */
	}
}</code></pre>
<h3 id="create-java-priority-queue-with-a-custom-comparator">Create Java PriorityQueue with a custom Comparator</h3>
- Create a Java PriorityQueue using a Custom Comparator that compares two Strings by their length:

<pre><code class="language-java">
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue<String> strQueue = new PriorityQueue<String>((Comparator<? super String>) new Comparator<String>() {
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });
		
		// Inserts the specified element into this priority queue.
		strQueue.offer("Jack");
		strQueue.offer("Charlie");
		strQueue.offer("Joe");
		strQueue.offer("George");
		
		while(!strQueue.isEmpty()) {
			System.out.print(strQueue.poll() + " ");
		}
	}
}</code></pre>

-> Output:

<pre><code class="language-java">
Joe Jack George Charlie
</code></pre>
<h2 id="java-priorityqueue-with-custom-object-example">Java PriorityQueue with Custom Object Example</h2>
- Create an Java Developer class:

<pre><code class="language-java">
class Developer{
	Integer id;
	String name;
	Double salary;
	
	public Developer(Integer id, String name, Double salary){
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	
	public int getId() {
		return this.id;
	}
	
	public String getName() {
		return this.name;
	}
	
	public Double getSalary() {
		return this.salary;
	}
	
	public String toString() {
		return String.format("[id = %d, name = %s, salary = %.2f]", id, name, salary);
	}
}</code></pre>

- Implement <code>Comparable</code> interface to compare its elements and order them accordingly as below:

<pre><code class="language-java">
class Developer implements Comparable<Developer>{
	...
	
	@Override
	public int compareTo(Developer d) {
        if(this.getSalary() > d.getSalary()) {
            return 1;
        } else if (this.getSalary() < d.getSalary()) {
            return -1;
        } else {
            return 0;
        }
	}
}</code></pre>

- Create a Java PriorityQueue Example with Developer class:

<pre><code class="language-java">
import java.util.PriorityQueue;
import java.util.Queue;

public class JavaPriorityQueueExamples {

	public static void main(String[] args) {
		Queue<Developer> devQueue = new PriorityQueue<Developer>();
		
		// Inserts the specified element into this priority queue.
		devQueue.offer(new Developer(1, "Jack", 6000.0));
		devQueue.offer(new Developer(4, "Joe", 7000.0));
		devQueue.offer(new Developer(10, "Davis", 6500.0));
		devQueue.offer(new Developer(6, "Mary", 5700.0));
		
		while(!devQueue.isEmpty()) {
			System.out.println(devQueue.poll());
		}		
	}
}</code></pre>

-> Output:

<pre><code class="language-java">
/*
 * [id = 6, name = Mary, salary = 5700,00]
 * [id = 1, name = Jack, salary = 6000,00]
 * [id = 10, name = Davis, salary = 6500,00]
 * [id = 4, name = Joe, salary = 7000,00]
 */</code></pre>

-> The Developer with smallest salary is removed first
<h2 id="conclusion">Conclusion</h2>
We had learned how to work with Java PriorityQueue by examples:
<ul>
<li>Create Java PriorityQueue with Natural Ordering of Elements.</li>
<li>Create Java PriorityQueue with Custom Comparator.</li>
<li>Create Java PriorityQueue with Custom Object that implements <code>Comparable</code> interface.</li>
<li>Do a list operations of Java PriorityQueue: <code>offer</code>, <code>peek</code>, <code>poll</code>, <code>remove</code>...</li>
</ul>

Happy Learning! See you later!