Curriculum
In Java, PriorityQueue is a class that implements the Queue interface and provides a way to store a collection of elements that can be accessed based on their priority. In this answer, I will explain how to use PriorityQueue in Java, as well as some of its commonly used methods.
To use PriorityQueue in Java, you must first import the java.util.PriorityQueue class. You can create a new PriorityQueue by specifying the initial capacity and an instance of a Comparator to define the order in which elements are stored. If you don’t specify a Comparator, elements are stored in their natural order (i.e., using their compareTo() method).
Here’s an example of how to create a new PriorityQueue that can hold elements of type String, using a Comparator that orders the elements based on their length:
PriorityQueue<String> queue = new PriorityQueue<>(10, Comparator.comparing(String::length));
Once a PriorityQueue has been created, elements can be added or removed from it using the following methods:
// Add an element to the queue
queue.offer("apple");
// Remove and return the head of the queue
String head = queue.poll();
// Return the head of the queue without removing it
head = queue.peek();
// Remove all elements from the queue
queue.clear();
PriorityQueue provides several methods to access elements in the queue:
// Get the number of elements in the queue
int size = queue.size();
// Check if the queue is empty
boolean isEmpty = queue.isEmpty();
// Convert the queue to an array
String[] array = queue.toArray(new String[0]);
// Iterate over the elements in the queue using a for-each loop
for (String element : queue) {
System.out.println(element);
}
Some other commonly used methods provided by the PriorityQueue class include:
// Add an element to the queue, throws an exception if the queue is full
queue.add("banana");
// Get the head of the queue, throws an exception if the queue is empty
head = queue.element();
// Get the comparator used to order the elements in the queue
Comparator<String> comparator = queue.comparator();
One important thing to keep in mind when using a PriorityQueue is that elements are stored in order based on their priority, not based on the order in which they were added. This means that when you iterate over the elements in the queue, they may not be returned in the order in which they were added. If you need to maintain the order in which elements were added, you may want to consider using a different data structure, such as a LinkedList.