将priorityQueue更改为max priorityqueue [英] Change priorityQueue to max priorityqueue

查看:179
本文介绍了将priorityQueue更改为max priorityqueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java的Integers中有优先级队列:

I have priority queue in Java of Integers:

 PriorityQueue<Integer> pq= new PriorityQueue<Integer>();

当我调用 pq.poll()我得到最小元素。

When I call pq.poll() I get the minimum element.

问题:如何更改代码以获取最大元素?

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

推荐答案

如何这样:

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);
}

Collections.reverseOrder()提供了一个 Comparator ,它将按照与它们的自然顺序相反的顺序对 PriorityQueue 这种情况。

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.

这篇关于将priorityQueue更改为max priorityqueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆