Java PriorityQueue Example

In post shows usage of PriorityQueue in Java with example.
A priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.

Java PriorityQueue Example

In this example, we are adding few Strings to the PriorityQueue, while creating PriorityQueue I have passed the Comparator(named as MyComparator) to the PriorityQueue constructor.
In the MyComparator java class, I have sorted the Strings based on their length, which means the priority that I have set in PriorityQueue is String length. That way I ensured that the smallest string would be served first rather than the string that I have added first.
import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {

        PriorityQueue < String > queue =
            new PriorityQueue < String > (15, new MyComparator());
        queue.add("Stark");
        queue.add("Tony");
        queue.add("Tom");
        queue.add("Mr");

        /*
         * What I am doing here is removing the highest priority element from Queue and
         * displaying it. The priority I have set is based on the string length. The
         * logic for it is written in Comparator
         */
        while (queue.size() != 0) {
            System.out.println(queue.poll());
        }
    }
}

class MyComparator implements Comparator < String > {
    @Override
    public int compare(String x, String y) {
        return x.length() - y.length();
    }
}

Output

Mr
Tom
Tony
Stark


Comments