将 priorityQueue 更改为最大优先级队列

新手上路,请多包涵

我在整数 Java 中有优先级队列:

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

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

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

原文由 Borut Flis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 603
2 个回答

像这样怎么样:

 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 中的元素进行排序。

原文由 Edwin Dalorzo 发布,翻译遵循 CC BY-SA 3.0 许可协议

从 Java 8 开始,您可以使用 lambda 表达式。

以下代码将打印更大的 10。

 // There is overflow problem when using simple lambda as comparator, as pointed out by Фима Гирин.
// PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);

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

pq.add(10);
pq.add(5);
System.out.println(pq.peek());

lambda 函数将两个 Integer 作为输入参数,将它们相减,并返回算术结果。 lambda 函数实现功能接口 Comparator<T> 。 (这是就地使用,而不是匿名类或离散实现。)

原文由 Guangtong Shen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题