订单未如预期
问题描述:
我有这样的测试:订单未如预期
@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);
}
我想到时Queue能根据我的比较顺序为:先排序最高值。相反,我得到这样的结果:
java.lang.AssertionError: expected:<[three, two, one]> but was:<[three, one, two]>
我的期望错了吗?
答
让我们来看看PriorityQueue
docs:
在方法迭代器设置()的迭代器并不保证遍历优先级队列中的元素的任何特定顺序。
同样适用于Stream
实例。
如果你想创建一个Stream
实例将遍历队列中的优先顺序,你可以这样做:
Stream.generate(queue::poll).limit(queue.size())
记住poll
ING将删除原来的队列中的元素。
好奇downvote。 – EJP
你应该提到,这*消耗*队列。也就是说,完成后,'queue'将是空的。 –
@JimMischel当然,好主意:) –