Priority Queue Example Java Program


Definition

A priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. While priority queues are often implemented with heaps, they are conceptually distinct from heaps.

Syntax

PriorityQueue Variable_name = new PriorityQueue();

Priority Queue Example Program

import java.util.Comparator;
import java.util.PriorityQueue;
 
public class PriorityQueueDemo {
	static class PQsort implements Comparator {
		public int compare(Integer one, Integer two) {
			return two - one;
		}
	}
	public static void main(String[] args) {
		int[] array = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
		PriorityQueue pq1 = new PriorityQueue();
 		for (int i : array) {
			pq1.offer(i);
		}
		System.out.println("PriorityQueue1: " + pq1);
		PQsort pqs = new PQsort();
		PriorityQueue pq2 = new PriorityQueue(10, pqs);
		for (int i : array) {
			pq2.offer(i);
		}
		System.out.println("PriorityQueue2: " + pq2);
 		System.out.println("size: " + pq2.size());
		System.out.println("peek: " + pq2.peek());
		System.out.println("size: " + pq2.size());
		System.out.println("poll: " + pq2.poll());
		System.out.println("size: " + pq2.size());
		System.out.print("PriorityQueue2: " + pq2);
 
	}
}

Sample Output

Output is:
PriorityQueue1: [1, 3, 5, 8, 4, 7, 6, 10, 9]
PriorityQueue2: [10, 9, 7, 8, 3, 5, 6, 1, 4]
size: 9
peek: 10
size: 9
poll: 10
size: 8
PriorityQueue2: [9, 8, 7, 4, 3, 5, 6, 1]