import java.util.PriorityQueue;
public class MaxHeapWithPriorityQueue {
public static void main(String args[]) {
// create priority queue
PriorityQueue<Integer> prq = new PriorityQueue<>(Comparator.reverseOrder());
// insert values in the queue
prq.add(6);
prq.add(9);
prq.add(5);
prq.add(64);
prq.add(6);
//print values
while (!prq.isEmpty()) {
System.out.print(prq.poll()+" ");
}
}
}
// min heap: PriorityQueue implementation from the JDK
PriorityQueue<Integer> prq = new PriorityQueue<>();
// max heap: PriorityQueue implementation WITH CUSTOM COMPARATOR PASSED
// Method 1: Using Collections (recommended)
PriorityQueue<Integer> prq = new PriorityQueue<>(Collections.reverseOrder());
// Method 2: Using Lambda function (may cause Integer Overflow)
PriorityQueue<Integer> prq = new PriorityQueue<>((a, b) -> b - a);
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.