Java > Java Collections Framework > Queue and Deque > Queue Interface (PriorityQueue)
PriorityQueue with Custom Comparator: Ordering Strings by Length
This example demonstrates using a PriorityQueue
with a custom comparator to order strings based on their length. This is useful when the natural ordering of the elements is not suitable for the desired priority.
Code Example
This code defines a Comparator
that compares strings based on their length. The PriorityQueue
is initialized with this comparator, which causes the strings to be ordered in the queue based on their length, with the shortest strings having higher priority. The Comparator.comparingInt(String::length)
is a concise way to create a comparator that compares integers derived from String lengths.
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueueStringLength {
public static void main(String[] args) {
// Custom comparator to order strings by length
Comparator<String> stringLengthComparator = Comparator.comparingInt(String::length);
// Initialize PriorityQueue with the custom comparator
Queue<String> stringQueue = new PriorityQueue<>(stringLengthComparator);
stringQueue.offer("Orange");
stringQueue.offer("Apple");
stringQueue.offer("Banana");
stringQueue.offer("Kiwi");
System.out.println("Strings in PriorityQueue (ordered by length):");
while (!stringQueue.isEmpty()) {
System.out.println(stringQueue.poll());
}
}
}
Benefits of Custom Comparator
Using a custom comparator allows you to define a specific ordering for elements in the PriorityQueue
that might not be their natural ordering. This provides flexibility in how elements are prioritized based on different criteria, such as length, alphabetical order (case-insensitive), or other application-specific attributes.
Real-Life Use Case
Imagine you are building an application that processes user input. You might want to prioritize shorter inputs to improve responsiveness. In this scenario, a PriorityQueue
with a custom comparator that orders strings by length can be used to efficiently manage and process the user input.
Handling Edge Cases with Comparators
When implementing a custom comparator, consider how to handle edge cases, such as null values or strings with special characters. You might want to add checks to handle these cases gracefully to prevent unexpected exceptions.
FAQ
-
What happens if I don't provide a comparator when using PriorityQueue?
If you don't provide a comparator, the elements in thePriorityQueue
must implement theComparable
interface, and the natural ordering will be used. If the elements do not implementComparable
, aClassCastException
will be thrown. -
Can I change the comparator of a PriorityQueue after it's been created?
No, you cannot change the comparator of aPriorityQueue
after it has been created. You need to create a newPriorityQueue
with the desired comparator.