Loading

Quipoin Menu

Learn • Practice • Grow

data-structure-with-java / PriorityQueue in Java
tutorial

PriorityQueue in Java

Java provides a PriorityQueue class that implements a min-heap by default. It is part of the Collections Framework and offers O(log n) for insertion and removal.

Basic usage:


PriorityQueue pq = new PriorityQueue<>(); // min-heap
pq.offer(5);
pq.offer(1);
pq.offer(3);
System.out.println(pq.peek()); // 1 (smallest)
System.out.println(pq.poll()); // 1
System.out.println(pq.poll()); // 3

Max-Heap using Comparator
To create a max-heap, pass a reverse comparator.


PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> b - a);
// or
PriorityQueue maxHeap2 = new PriorityQueue<>(Collections.reverseOrder());

Custom objects:
Either implement Comparable or provide a Comparator.


class Task implements Comparable {
int priority;
public int compareTo(Task other) {
return this.priority - other.priority; // min-heap by priority
}
}
PriorityQueue pq = new PriorityQueue<>();
Two Minute Drill
  • PriorityQueue in Java is a min-heap by default.
  • Use offer() for insert, poll() for remove, peek() for top.
  • To get max-heap, provide reverse comparator.
  • Time complexity: O(log n) for insert and remove, O(1) for peek.

Need more clarification?

Drop us an email at career@quipoinfotech.com