how to use heap class in 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 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: heap in java

In Java PriorityQueue can be used as a Heap.

Min Heap
PriorityQueue minHeap = new PriorityQueue<>();


Max Heap:
PriorityQueue maxHeap = new PriorityQueue<>(Comparator.reverseOrder());

Tags:

Misc Example