C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For: We use the for-loop to display all the elements in the queue. Notice how it goes from first-sorted to last (bird comes before cat).
Java program that uses PriorityQueue
import java.util.PriorityQueue;
public class Program {
    public static void main(String[] args) {
        PriorityQueue<String> queue = new PriorityQueue<>();
        // Add 2 strings to PriorityQueue.
        queue.add("cat");
        queue.add("bird");
        // Loop over and display contents of PriorityQueue.
        for (String element : queue) {
            System.out.println(element);
        }
    }
}
Output
bird
cat
Java program that uses peek
import java.util.PriorityQueue;
public class Program {
    public static void main(String[] args) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        // Add data to PriorityQueue.
        queue.add(1);
        queue.add(100);
        queue.add(0);
        queue.add(1000);
        // Use peek.
        // ... The element that is sorted first is returned.
        // ... The queue is not changed.
        int peeked = queue.peek();
        System.out.println(peeked);
    }
}
Output
0
Here: We loop infinitely over the PriorityQueue until it has 0 elements. We print all the internally-sorted elements.
Java program that uses poll
import java.util.PriorityQueue;
public class Program {
    public static void main(String[] args) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        // Add data.
        queue.add(1);
        queue.add(100);
        queue.add(0);
        queue.add(1000);
        // Poll all elements in the PriorityQueue.
        while (queue.size() > 0) {
            // Get polled element and print it.
            int polled = queue.poll();
            System.out.println(polled);
        }
    }
}
Output
0
1
100
1000
And: This can simplify code. It can make using elements that must be accessed in a sorted way easier.