Course contentsShow
← Java
Lesson 1185 of 2,87027. Queue and Deque ImplementationsFree lesson

Creating a PriorityQueue with a Custom Comparator

Provide a Comparator to define custom priority ordering, such as reverse order or domain-specific priorities.

Creating a PriorityQueue with a Custom Comparator

You'll learn how to control the priority ordering in a PriorityQueue by supplying your own comparison logic.

By default, a PriorityQueue uses natural ordering (smallest element first), but you can completely customize this behavior by providing a Comparator when creating the queue. This lets you define exactly what "highest priority" means for your application—whether it's reverse order, domain-specific rules, or complex multi-field comparisons.

Why Use a Custom Comparator?

Sometimes natural ordering doesn't match your needs. Perhaps you want largest-first instead of smallest-first. Or maybe you're queuing tasks where priority depends on urgency levels, deadlines, or other business logic that has nothing to do with natural ordering.

Think of it like changing the rules at a waiting room: instead of "first come, first served," you might prioritize emergency cases, then urgent cases, then routine appointments—your custom rules determine who goes next.

How to Provide a Comparator

Pass a Comparator to the PriorityQueue constructor:

// Reverse order: largest integers have highest priority
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.offer(5);
maxHeap.offer(10);
maxHeap.offer(3);
System.out.println(maxHeap.poll()); // 10 (largest)

You can also create custom comparison logic:

// Strings by length (shortest first)
PriorityQueue<String> byLength = new PriorityQueue<>(
    Comparator.comparingInt(String::length)
);
byLength.offer("apple");
byLength.offer("kiwi");
byLength.offer("banana");
System.out.println(byLength.poll()); // "kiwi" (length 4)

Domain-Specific Priorities

For custom objects, define exactly what determines priority based on your application's needs—not just the object's natural ordering.

Key Takeaway: A custom Comparator gives you full control over what "highest priority" means in your PriorityQueue, enabling reverse ordering, multi-field comparisons, or any domain-specific priority rules your application requires.