优先级队列的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 楼答案
让我们来看看
PriorityQueue
{a1}:这同样适用于
Stream
实例如果要创建一个
Stream
实例,该实例将按优先级顺序遍历队列,可以执行以下操作:请记住
poll
将从原始队列中删除元素