how to create min heap and max heap in java code example

Example 1: create a min heap in java using priority queue

int arr[]={1,2,1,3,3,5,7};
        PriorityQueue a=new PriorityQueue<>();
        for(int i:arr){
            a.add(i);
        }
        while(!a.isEmpty())
            System.out.println(a.poll());

Example 2: min max heap java

// min heap: PriorityQueue implementation from the JDK
PriorityQueue prq = new PriorityQueue<>();

// max heap: PriorityQueue implementation WITH CUSTOM COMPARATOR PASSED
// Method 1: Using Collections (recommended)
PriorityQueue prq = new PriorityQueue<>(Collections.reverseOrder());
// Method 2: Using Lambda function (may cause Integer Overflow)
PriorityQueue prq = new PriorityQueue<>((a, b) -> b - a);

Tags:

Misc Example