Appearance
How do I use a PriorityQueue?
A PriorityQueue is a queue data structure that manages elements by priority. In Java, you can use the java.util.PriorityQueue class to create a min-heap-based priority queue, which pops the element with the lowest priority first.
Here's an example of how to create a PriorityQueue and add elements to it:
java
import java.util.PriorityQueue;
// Create a priority queue
PriorityQueue<Integer> pq = new PriorityQueue<>();
// Add an element with a priority of 10
pq.add(10);
// Add an element with a priority of 5
pq.add(5);
// Add an element with a priority of 1
pq.add(1);
// The queue now looks like this:
// [1, 5, 10]To pop an element off the queue, use the poll() method:
java
// Pop the element with the lowest priority (i.e., 1)
System.out.println(pq.poll()); // Output: 1
// Pop the element with the next lowest priority (i.e., 5)
System.out.println(pq.poll()); // Output: 5
// Pop the element with the highest priority (i.e., 10)
System.out.println(pq.poll()); // Output: 10
// The queue is now emptyYou can also initialize a PriorityQueue directly from a collection, which automatically arranges the elements into a heap:
java
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
// Convert a regular list into a priority queue
List<Integer> list = Arrays.asList(10, 5, 1);
PriorityQueue<Integer> pq = new PriorityQueue<>(list);
// The queue is now a heap
System.out.println(pq); // Output: [1, 5, 10]By default, Java's PriorityQueue is a min-heap. To create a max-heap (where the highest priority element is popped first), pass Collections.reverseOrder() to the constructor:
java
import java.util.Collections;
import java.util.PriorityQueue;
PriorityQueue<Integer> maxPq = new PriorityQueue<>(Collections.reverseOrder());
maxPq.add(10);
maxPq.add(5);
maxPq.add(1);
System.out.println(maxPq.poll()); // Output: 10I hope this helps! Let me know if you have any questions.