min max heap java code example
Example 1: max heap java
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()+" ");
}
}
}
Example 2: create a min heap in java using priority queue
int arr[]={1,2,1,3,3,5,7};
PriorityQueue<Integer> a=new PriorityQueue<>();
for(int i:arr){
a.add(i);
}
while(!a.isEmpty())
System.out.println(a.poll());
Example 3: min max heap java
// 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);