PriorityQueue
This collection keeps all elements in a sorted order. Integers are kept ordered from low to high. Strings are kept ordered from first alphabetically to last.
We add elements, and they are stored in the PriorityQueue
. Then we use peek()
to see the first element in the queue. We use poll()
to get and remove the first element.
Here we create a PriorityQueue
and add 2 strings to it. The PriorityQueue
is generic so we must specify a type for its elements.
for
-loop to display all the elements in the queue. Notice how it goes from first-sorted to last (bird comes before cat).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); } } }bird cat
This method returns the first element in the PriorityQueue
(this is the one that is sorted to be first). The contents of the queue are not modified.
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); } }0
This method returns the first element in the PriorityQueue
and removes it. So the queue's size is reduced by 1. We can call poll()
in a loop that checks the size.
PriorityQueue
until it has 0 elements. We print all the internally-sorted elements.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); } } }0 1 100 1000
With PriorityQueue
we can access a collection in a sorted order, even without sorting it. We call peek()
and poll()
to get the first-sorted element.
With PriorityQueue
we have a collection that lets us access data in order—we poll()
the first elements, and add them in any order. This helps programs that need priority-based processing.