Search code examples
scalapriority-queue

Scala - Ordering fails for PriorityQueue


I am trying to create a simple priority queue in Scala:

val priorities: mutable.PriorityQueue[Priority] = mutable.PriorityQueue(
 Priority(2, 302),
 Priority(3, 300),
 Priority(5, 400),
 Priority(4, 309),
 Priority(1, 301)
)(Ordering.by[Priority, Int](_.priority).reverse)

case class Priority(priority: Int, value: Int)

And when I do
priorities.foreach(p => println(p.priority, p.value))

The output I expect is:

(1,301)
(2,302)
(3,300)
(4,309)
(5,400)

But instead, I get:

(1,301)
(2,302)
(5,400)
(4,309)
(3,300)

As you can see, there is some problem with the ordering. Can I please get some insights about where I am going wrong and what shall I do to get the desired output?


Solution

  • The foreach method processes all the elements of the PriorityQueue but not necessarily in the sorted order. If you remove the elements you can see that the ordering is working:

    while (priorities.nonEmpty) println(priorities.dequeue())
    
    Priority(1,301)
    Priority(2,302)
    Priority(3,300)
    Priority(4,309)
    Priority(5,400)
    

    The implementation keeps the first element as the highest priority element but the remainder are unsorted. dequeue will bring the new highest priority element to the front.

    There does not appear to be a non-destructive way to show the whole PriorityQueue in order.