In this shot, we will learn how to use the PriorityQueue.poll()
method in Java.
The PriorityQueue.poll()
method is present in the PriorityQueue
class inside the java.util
package.
The PriorityQueue.poll()
method is used to remove the element present at the head of the PriorityQueue
.
public E poll();
This method does not accept any parameters.
This method returns either of the values mentioned below:
PriorityQueue
.PriorityQueue
is empty.Let us have a look at the code now.
import java.util.*;class Main{public static void main(String[] args){PriorityQueue<Integer> pq = new PriorityQueue<Integer>();pq.add(2);pq.add(28);pq.add(6);pq.add(80);pq.add(28);pq.add(7);pq.add(15);System.out.println("Elements in the priority queue are: " + pq);System.out.println("Head Element removed from the priority queue is: " + pq.poll());System.out.println("Elements after removing head element in the priority queue are: " + pq);}}
Line 1: We import the required package.
Line 2: We make a Main
class.
Line 4: We make a main()
function.
Line 6: We declare a PriorityQueue
, which consists of integers.
Lines 8-14: We insert the elements into the PriorityQueue
by using the PriorityQueue.add()
method.
Line 16: We display the elements present in the priority queue.
Line 18: We print the head element which is removed from the priority queue.
Line 20: We print the priority queue again and we can verify that the element has been removed.
So, this way, we can use the PriorityQueue.poll()
method to remove the head element from the priority queue data structure in Java.