PriorityQueue 的顺序不符合预期

Order of PriorityQueue not as expected

我有这个测试:

@Test
public void testPrioQueue() {
    PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
    pq.add(new SimpleEntry<>("one", 1));
    pq.add(new SimpleEntry<>("three", 3));
    pq.add(new SimpleEntry<>("two", 2));
    List<String> keys = pq.stream().map(e -> e.getKey()).collect(Collectors.toList());
    assertEquals(Arrays.asList("three", "two", "one"), keys);
}

我希望 PriorityQueue 根据我的比较器排序:首先按最高值排序。相反,我得到了这个结果:

java.lang.AssertionError: expected:<[three, two, one]> but was:<[three, one, two]>

我的预期有误吗?

我们来看看PriorityQueue docs:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.

同样适用于 Stream 个实例。

如果你想创建一个 Stream 实例来按优先级顺序遍历队列,你可以这样做:

Stream.generate(queue::poll).limit(queue.size())

请记住,polling 将从原始队列中删除元素。