Bijan
0
Q:

priority queue max heap in 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()+" ");
        }
    }

}
3
//Sol1
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());


//Sol2
// PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
PriorityQueue<Integer> pq =new PriorityQueue<>((x, y) -> Integer.compare(y, x));


//Sol3
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(defaultSize, new Comparator<Integer>() {
    public int compare(Integer lhs, Integer rhs) {
        if (lhs < rhs) return +1;
        if (lhs.equals(rhs)) return 0;
        return -1;
    }
});
0
PriorityQueue<Integer> maxPriorityQ = new PriorityQueue<Integer>(Collections.reverseOrder());
0
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());
0

New to Communities?

Join the community