Command Palette

Search for a command to run...

Back to the lesson: Topic 9.8 — PriorityQueue
Core Java · Example 3 of 5

Custom priorities, max-heaps and tie-breaking

Without thenComparing, the two priority-2 tasks could come out in either order.

PriorityQueue always hands out the smallest element first (or the largest, with a reversed comparator). It's a binary heap stored in an array: peek is O(1), offer and poll are O(log n), and its iteration order is not sorted.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Merge the sorted arrays {1, 4, 7}, {2, 5, 8} and {3, 6, 9} into one sorted list using a PriorityQueue<int[]> holding {value, arrayIndex, elementIndex}.

02

Return the 2 most frequent words in ["tea", "cake", "tea", "chai", "cake", "tea"], using a HashMap for counts and a PriorityQueue for the top 2.

03

Simulate a meeting-room scheduler: given meetings {0, 30}, {5, 10} and {15, 20} (start, end), compute the minimum number of rooms needed using a min-heap of end times.

Explain it without notes

01

How is PriorityQueue implemented, and what are the costs of offer, poll, peek, remove(Object) and contains?

02

Why doesn't printing a PriorityQueue show sorted order?

03

How do you find the k largest elements of a large array efficiently, and what is the complexity?

04

How do you make a max-heap in Java, and what's wrong with (a, b) -> b - a?

Custom priorities, max-heaps and tie-breaking
Sign in to run this example in your browser.

Expected output

1 fix outage
2 answer email
2 write report
3 book travel
max-heap polls: 9 7