Priority Queue is a special type of queue data structure that holds elements in order of their priority. In Java, it is implemented using PriorityQueue class.
Reason
Priority Queue is useful when dealing with tasks that need to be executed in order of their priority. It can also be used to efficiently implement schedulers.
Example code with output
import java.util.PriorityQueue;
public class PriorityQueueTest {
public static void main(String args[]) {
PriorityQueue queue = new PriorityQueue<>();
queue.add("John");
queue.add("Lee");
queue.add("Sam");
queue.add("Cat");
System.out.println("Head value using peek function:" + queue.peek());
System.out.println("The queue elements:");
queue.forEach(e -> System.out.println(e));
queue.remove();
queue.poll();
System.out.println("After removing two elements:");
queue.forEach(e -> System.out.println(e));
}
}
Output
:
Head value using peek function:Cat
The queue elements:
Cat
John
Lee
Sam
After removing two elements:
John
Lee
Related Quiz:
UnicodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte, python
How to Edit Shopify Themes Locally Using Git and Theme Kit
Get LinkedIn skill assessments with Quiz Solver plugin
Wordpres plugin Advanced Quiz Post plugin
AttributeError: 'module' object has no attribute 'function_name'
Project Java Build Form by multiple process
OSError: [Errno 2] No such file or directory: 'file_name', in python
NameError: name 'x' is not defined python