Borut Flis Borut Flis - 4 months ago 32
Java Question

Change priorityQueue to max priorityqueue

I have priority queue in Java of Integers:
PriorityQueue pq= new PriorityQueue();
When I call

pq.poll()
I get the minimum element.

Question: how to change the code to get the maximum element?

Answer

How about like this:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...

Integer val = null;
while( (val = queue.poll()) != null) {
    System.out.println(val);
}

The Collections.reverseOrder() provides a Comparator that would sort the elements in the PriorityQueue in a the oposite order to their natural order in this case.