在 MinMaxPriorityQueue 番石榴中更改比较器

Change Comparator in MinMaxPriorityQueue guava

我最近在与 MinMaxPriorityQueue 合作。我的目标是从一些文本文件中获取顶级元素。队列正在使用 Ordering.natural(),但我想将其更改为 Ordering.natural().reverse()。没用,不知道怎么设置。

Comparator<Long> comp = Ordering.natural().reverse();
MinMaxPriorityQueue<Long> pq = MinMaxPriorityQueue.maximumSize(11).create();
pq.orderedBy(comp);
System.out.println(pq.comparator());

无论如何输出returnsOrdering.natural()。我该如何管理? 非常感谢!

Guava 的 MinMaxPriorityQueue 状态文档:

... the queue's specified comparator. If no comparator is given at construction time, the natural order of elements is used.

应该是

Comparator<Long> comp = Ordering.natural().reverse();
MinMaxPriorityQueue<Long> pq = MinMaxPriorityQueue.orderedBy(comp)
        .maximumSize(11).create();

如您所见,in the docs MinMaxPriorityQueue#orderedBy 是静态方法,returns 是 Builder。您应该只通过 class 调用该方法,它应该告诉您该方法 不操作实例 .

Guava 使用 Builder 模式:它不是提供改变实例行为的方法,而是提供在实例化之前设置该行为的可能性(通过 Builder)。您在 Builder 上设置属性并调用 Builder#create 来获取实例。

有关详细信息,请参阅 this question and this one or read on wikipedia

您必须在创建队列时传递 Comparator 否则默认顺序为 Ordering.natural()。根据 javadocs

If no comparator is given at construction time, the natural order of elements is used.

因此,如果您需要反向排序,请通过传递 Comparator

创建您的队列
Comparator<Long> comp = Ordering.natural().reverse();
MinMaxPriorityQueue<Long> pq = MinMaxPriorityQueue.orderedBy(comp).maximumSize(11).create();