I have priority queue in Java of Integers:
PriorityQueue<Integer> pq= new PriorityQueue<Integer>();
When I call pq.poll()
I get the minimum element.
Question: how to change the code to get the maximum element?
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.