How to use PriorityQueue in java?
(Binary Heap)
“Hi There”, We have learned about Binary Heap in our previous articles. If you miss those reads, recommend you to quickly go through the following reads about Heap.
In this article will see how Heap was implemented for PriorityQueue in Java
The PriorityQueue class implements the Queue Interface in Java. A PriorityQueue is beneficial when the objects are supposed to be processed based on priority rather than the First-In-First-Out (FIFO) algorithm, which is usually implemented in the Queue interface. The internal working of the PriorityQueue is based on the Binary Heap.
The elements of the priority queue are ordered according to the natural ordering, or by a comparator provided at the construction time of the queue, depending on which constructor is used.
“So we can set a comparator through PriorityQueue Constructor to generate priority-based mInHeap or MaxHeap. Default comparator is with Natural sorting order (low to high or MinHeap based)”
1. MinHeap-based PriorityQueue Constructor (default behaviour):
PriorityQueue<Integer> max = new PriorityQueue<>((x, y) -> Integer.compare(x,y));
2. MaxHeap-based PriorityQueue Constructor:
PriorityQueue<Integer> max = new PriorityQueue<>((x, y) -> Integer.compare(y, x));
Below is the visualization of implementing a PriorityQueue. The lowest number has the highest priority by default.

Java Implementation:
O/P:

Thanks for your read and 👏👏
Will see you in the next read.
#arraysinjava. #array #datastructures #codinginterviewquestions #codinginterview #faang #leetcode #animated #java #python #faang #motion