Skip to main content

How do I retrieve items from a queue in priority order

In this Q&A, we'll go over how to create and retrieve elements from a queue in priority order

Java provides PriorityQueue class.  It provides an option to create a queue with a Comparator object.

Couple of additional points to keep in mind when using this class
  - Iterator and forEach methods do no guarantee traversal in priority order
  - enqueue and deenqueue method have log n performance

Example:

import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueTest {
    public static void main(String[] args ) {
        Comparator<Integer> c = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return (o2 < o1) ? -1 : ((o2 == o1) ? 0 : 1);
            }
        };
        PriorityQueue<Integer> pq = new PriorityQueue<>(10, c);
        for(int i = 0; i < 10; ++i)
            pq.add(i);
            for(int i = 0; i < 10; ++i)
               System.out.println(pq.poll());
    }
}

Comments