Java Create a Priority Queue with a Custom Comparator

Let’s say that we need to create a priority queue of String elements in which the String with the smallest length is processed first.

We can create such a priority queue by passing a custom Comparator that compares two Strings by their length.
Here is an example -
import java.util.Comparator;
import java.util.PriorityQueue;

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

        Comparator < String > stringLengthComparator = (s1, s2) - > {
            return s1.length() - s2.length();
        };

        // Create a Priority Queue with a custom Comparator
        PriorityQueue < String > namePriorityQueue = new PriorityQueue < > (stringLengthComparator);

        // Add items to a Priority Queue (ENQUEUE)
        namePriorityQueue.add("Ramesh");
        namePriorityQueue.add("John");
        namePriorityQueue.add("Tom");
        namePriorityQueue.add("Tony");
        namePriorityQueue.add("Amir");
        namePriorityQueue.add("Prabhas");

        // Remove items from the Priority Queue (DEQUEUE)
        while (!namePriorityQueue.isEmpty()) {
            System.out.println(namePriorityQueue.remove());
        }
    }
}

Output

Tom
Tony
Amir
John
Ramesh
Prabhas

Comments