Min Heap Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Min Heap runs in O(log n) time and O(n) space, in Java as in every other language.
- ✓java.util.PriorityQueue is a binary min-heap and is a min-heap BY DEFAULT, it orders by natural ordering, or by a Comparator passed to the constructor.
- ✓Pass a Comparator explicitly whenever the elements are not trivially comparable, and prefer Comparator.comparingInt over a lambda that subtracts, subtraction overflows for large or negative values and produces a comparator that violates its own contract.
- ✓The Java trap: PriorityQueue does not iterate in priority order, and its toString reflects the internal array layout.
- ✓offer and poll are O(log n) with an array-backed heap that grows by roughly 50% on resize.
What Min Heap actually is
Min Heap in Java: what you actually reach for
Java implementation
import java.util.Comparator;
import java.util.PriorityQueue;
record Task(String name, int cost) {}
public class Example {
public static void main(String[] args) {
// Min-heap BY DEFAULT, no Reverse wrapper needed.
PriorityQueue<Task> queue = new PriorityQueue<>(
16, Comparator.comparingInt(Task::cost) // never (a,b) -> a.cost - b.cost
);
queue.offer(new Task("b", 5));
queue.offer(new Task("a", 1));
queue.offer(new Task("c", 8));
// Iteration is NOT sorted, only repeated poll() is.
System.out.println(queue); // heap order, looks "wrong"
while (!queue.isEmpty()) {
System.out.println(queue.poll()); // a, b, c
}
// Max-heap:
PriorityQueue<Integer> maxHeap =
new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.addAll(java.util.List.of(3, 9, 1));
System.out.println(maxHeap.poll()); // 9
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Min Heap?
java.util.PriorityQueue is a binary min-heap and is a min-heap BY DEFAULT, it orders by natural ordering, or by a Comparator passed to the constructor. Comparator.reverseOrder() or Comparator.comparingInt(...).reversed() turns it into a max-heap. For concurrent use, PriorityBlockingQueue is the drop-in equivalent.
What is the most common Java mistake when implementing Min Heap?
PriorityQueue does not iterate in priority order, and its toString reflects the internal array layout. So printing the queue, streaming it, or looping over it with for-each gives you an order that is NOT sorted, which reads as a bug in your comparator and is not. Only repeated poll() yields sorted output. Also remove(Object) is O(n) because it must search the array, so there is no efficient decrease-key.
How does Min Heap actually perform in Java?
offer and poll are O(log n) with an array-backed heap that grows by roughly 50% on resize. The heavy cost is boxing: a PriorityQueue<Integer> allocates an Integer per element outside the -128..127 cache and makes the array pointer-dense. For primitive workloads use fastutil's IntHeapPriorityQueue or an int[] heap. peek is O(1). Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.