有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

优先级队列的java顺序不符合预期

我有一个测试:

@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]>

我的期望错了吗


共 (1) 个答案

  1. # 1 楼答案

    让我们来看看PriorityQueue{a1}:

    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())
    

    请记住poll将从原始队列中删除元素