Search code examples
javacollectionspriority-queue

Order of PriorityQueue not as expected


I have this test:

@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);
}

I expect the PriorityQueue to order according to my comparator: sort by highest value first. Instead I get this result:

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

Is my expectation wrong?


Solution

  • Let's have a look at PriorityQueue docs:

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

    Same applies to Stream instances.

    If you want to create a Stream instance that would traverse the queue in the order of priorities, you can do something like:

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

    Keep in mind that polling will remove elements from the original queue.