Borut Flis Borut Flis - 1 year ago 159
Java Question

Change priorityQueue to max priorityqueue

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

I get the minimum element.

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

Answer Source

How about like this:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());

Integer val = null;
while( (val = queue.poll()) != null) {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download