erdal.karaca erdal.karaca - 1 month ago 9
Java Question

Order of PriorityQueue not as expected

I have this 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 = -> 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?

Answer Source

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: