PriorityQueue Custom Comparator Dispatch
Rank work by severity with a PriorityQueue comparator: poll always yields the highest priority element, no matter the insertion order.
Code
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class IncidentDispatch {
record Incident(String service, int severity) {}
public static void main(String[] args) {
// 反转比较器:severity 越大越先出堆
Queue<Incident> queue = new PriorityQueue<>(
Comparator.comparingInt(Incident::severity).reversed());
queue.offer(new Incident("web", 3));
queue.offer(new Incident("db", 9));
queue.offer(new Incident("cache", 5));
// poll 按 priority 出队,与插入顺序无关
while (!queue.isEmpty()) {
Incident top = queue.poll();
System.out.println("dispatch: " + top.service() + " severity " + top.severity());
}
// 注意:iterator 不是有序遍历,只有 poll/peek 才按堆序返回
Queue<Integer> nums = new PriorityQueue<>(Arrays.asList(7, 2, 9, 4));
System.out.println("heap head: " + nums.peek());
}
}How it works
PriorityQueue Custom Comparator Dispatch keeps everything in the classes IncidentDispatch and Incident and the function main.
Repetition is confined to while (!queue.isEmpty()) — the rest of the file is straight-line.
Putting it to use
Look for the dispatch:, heap head: prefixes when the file runs; they tie each line to its step.
Core lines
Queue<Integer> nums = new PriorityQueue<>(Arrays.asList(7, 2, 9, 4));
queue.offer(new Incident("cache", 5));
queue.offer(new Incident("web", 3));
Interactive Tools for This Topic
FAQ
- What does PriorityQueue Custom Comparator Dispatch print when run?
- No setup needed: run the file and look for labeled lines like `dispatch:`, `heap head:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.