Priority queue in Java
In this post, you will learn how to implement a Priority Queue in Java programming language.
The priority of the element is used to determine the order in which the elements will be processed. The elements in the priority queue have some priority. In this element, it is inserted and deleted based on its priority.
The basic examples of Priority Queue are-
- Routing
- Operating System Scheduler
- Dijkstra's Shortest Path Algorithm
- Huffman Coding
These are the rules for processing elements in a priority queue.
- The element with the highest priority is processed first.
- The two elements with equal priority are processed based on a First Come First Serve(FCFS) basis.
The priority of the elements is set based on several factors. This is basically used in the operating system to execute the most priority process first. If this is set on the CPU time, then the element with the lowest execution time is executed first. Suppose there are two processes in a queue, one has 5ns execution time and the other has 10ns execution time, then the process having 5ns executes first.
Java program to insert a given element into a priority queue
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
//Creating Priority Queue
PriorityQueue pq = new PriorityQueue();
// adding items in the Priority Queue
pq.add("One");
pq.add("Two");
pq.add("Three");
pq.add("Four");
System.out.println("Original Priority Queue: "+pq);
// Inserting the specified item into the priority queue.
pq.offer("Five");
System.out.println("New Priority Queue: "+pq);
// deleting items in the Priority Queue
String str1 = pq.remove();
System.out.println("Element removed: "+str1);
String str2 = pq.remove();
System.out.println("Element removed: "+str2);
System.out.println("New Priority Queue: "+pq);
String str3 = pq.poll();
System.out.println("Head of this queue: "+str3);
System.out.println("New Priority Queue: "+pq);
}
}
Output of the above code:
Original Priority Queue: [Four, One, Three, Two]
New Priority Queue: [Five, Four, Three, Two, One]
Element removed: Five
Element removed: Four
New Priority Queue: [One, Two, Three]
Head of this queue: One
New Priority Queue: [Three, Two]
Related Articles
Sort array in ascending order JavaAutomorphic number in Java
Pascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java