2017-08-23 130 views
0

我有這樣的測試:訂單未如預期

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

我的期望錯了嗎?

回答

1

讓我們來看看PriorityQueuedocs

在方法迭代器設置()的迭代器並不保證遍歷優先級隊列中的元素的任何特定順序。

同樣適用於Stream實例。

如果你想創建一個Stream實例將遍歷隊列中的優先順序,你可以這樣做:

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

記住poll ING將刪除原來的隊列中的元素。

+1

好奇downvote。 – EJP

+0

你應該提到,這*消耗*隊列。也就是說,完成後,'queue'將是空的。 –

+0

@JimMischel當然,好主意:) –