In Java, PriorityQueue is a class that implements the Queue interface. It is an unbounded queue that orders its elements according to their natural order or by a specified Comparator. The element with the highest priority is placed at the front of the queue and the element with the lowest priority is placed at the end of the queue.
Creating a PriorityQueue
To create a PriorityQueue, we can use the following constructor:
PriorityQueue<E> pq = new PriorityQueue<>();
Here, E is the type of elements that we want to store in the PriorityQueue. If we want to store integers, for example, we can create a PriorityQueue as follows:
PriorityQueue<Integer> pq = new PriorityQueue<>();
We can also specify a Comparator to order the elements in the queue. A Comparator is an object that implements the Comparator interface. We can create a custom Comparator and use it to order the elements in the queue. To do this, we can use the following constructor:
PriorityQueue<E> pq = new PriorityQueue<>(Comparator);
Here, Comparator is an object that implements the Comparator interface. For example, if we want to order the elements in the queue based on their length (for strings), we can create a custom Comparator as follows:
Comparator<String> stringLengthComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
PriorityQueue<String> pq = new PriorityQueue<>(stringLengthComparator);
Adding elements to a PriorityQueue
We can add elements to the PriorityQueue using the add() or offer() methods:
pq.add(element);
pq.offer(element);
Both methods add the element to the end of the queue and then re-order the elements based on their priority.
Removing elements from a PriorityQueue
We can remove elements from the PriorityQueue using the remove() or poll() methods:
pq.remove();
pq.poll();
Both methods remove the element at the front of the queue (i.e., the element with the highest priority) and return it.
Accessing the element at the front of the PriorityQueue
We can access the element at the front of the PriorityQueue using the peek() method:
pq.peek();
This method returns the element at the front of the queue without removing it.
Conclusion
PriorityQueue is a useful class in Java for implementing priority-based algorithms. It provides an efficient way to maintain a queue of elements with priorities.