import java.util.PriorityQueue; public class Main { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(30); pq.add(10); pq.add(20); pq.add(40); while (!pq.isEmpty()) { System.out.print(pq.poll() + " "); } } }
The PriorityQueue in Java by default orders elements in natural ascending order (min-heap). So polling returns elements from smallest to largest.
A Priority Queue always ensures that the element with the highest priority (smallest or largest depending on implementation) is accessed first, not that all elements are sorted internally.
The poll() method returns null if the queue is empty. It does not throw an exception.
import java.util.PriorityQueue; import java.util.Comparator; public class Main { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder()); pq.add(5); pq.add(1); pq.add(3); pq.add(4); while (!pq.isEmpty()) { System.out.print(pq.poll() + " "); } } }
Using Comparator.reverseOrder() makes the PriorityQueue behave like a max-heap, so polling returns elements from largest to smallest.
import java.util.PriorityQueue; public class Main { public static void main(String[] args) { PriorityQueue<String> pq = new PriorityQueue<>(); pq.add("apple"); pq.add("banana"); pq.add("cherry"); pq.poll(); pq.add("date"); pq.poll(); pq.add("elderberry"); pq.poll(); System.out.println(pq.size()); } }
Initially 3 elements added. Then poll removes smallest. Add one, poll removes smallest again, add one, poll removes smallest again. Final count is 2.
