Codectionary / Developer documentation / Java

PriorityQueue Scheduling

PriorityQueue removes the least element according to natural ordering or a supplied comparator. Its iterator does not promise sorted traversal. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

queue.offer(value); queue.poll(); queue.peek()

Examples

PriorityQueue Scheduling

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.util.PriorityQueue;

public class Main {
  public static void main(String[] args) throws Exception {
    PriorityQueue<Integer> priorities = new PriorityQueue<>();
    priorities.offer(30);
    priorities.offer(10);
    priorities.offer(20);
    while (!priorities.isEmpty()) System.out.println(priorities.poll());
  }
}
  1. Expected output: 10 20 30
  2. Repeated poll calls retrieve priorities in ascending order. Printing or iterating the queue directly would not guarantee that order.

Best practices

  • Use a comparator to order domain objects by priority.
  • Do not mutate comparison fields while an item is queued.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading