Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
queue

What is the PriorityQueue.poll() method in Java?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

Syntax

public E poll();

Parameter

This method does not accept any parameters.

Return

This method returns either of the values mentioned below:

  • The Element present at the head of the PriorityQueue.
  • Null if the PriorityQueue is empty.

Code

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);
}
}
Use PriorityQueue.poll() method in Java

Explanation:

  • 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.

RELATED TAGS

java
communitycreator
queue

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring