Priority Queue with Custom Order in Java: Explanation & Practice

Use PriorityQueue with custom comparator

Problem summary

Create a PriorityQueue that orders tasks by priority (lower number = higher priority).

Starter code

import java.util.*;

// Task with name and priority

public class Main {
    public static void main(String[] args) {
        // Add tasks and process in priority order
    }
}

Expected output and test cases

  • Priority order
    Urgent
    Normal
    Low
  • 4 priorities
    Critical
    High
    Medium
    Low
  • Single task
    Only

Hints

  1. PriorityQueue with Comparator
  2. Compare by priority field
  3. poll() returns highest priority

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler