Implement polling in Java with poll() method

Hey Everyone! In this article, we will learn how to implement polling with the help of poll() method java.util.Queue package in Java.


First, let us study the Queue interface present in the java.util package in Java.

Queue interface

The queue interface is present in the java.util package in Java. The queue is an ordered set of elements that follows the First In First Out principle better known as FIFO. It extends the Collection interface. Priority Queue and Linked list classes in Java are present in the Queue interface. There are various methods present in Queue such as add(), peak(), element(), poll()etc.

poll() method in Java

The poll() method is present in the Queue interface (java.util package)
The poll() method is used to remove the element present at the front of the Queue and return it. It deletes the element from the container.
The method returns null when the Queue is empty.

Let’s have a look at the program code to understand it.

Java Code to use poll() method


package program10;

import java.util.*;
//importing the Queue interface

public class Program10 {


    public static void main(String[] args) {
        
        Queue<Character> dq =new ArrayDeque<>();
        
        //add elements to the queue
        
        for ( char i = 'a'; i  <  'f'; i++ ) {  
         dq.add(i); 
      }
        
        //displaying the queue
        System.out.println("The Queue is "+dq);
        
        System.out.println("The element at the front of the queue is "+dq.poll());
            
        System.out.println("The Queue now is "+dq);
    }
    
}
Output:-

The Queue is [a, b, c, d, e]
The element at the front of the queue is a
The Queue now is [b, c, d, e]

I hope that the article was useful to you.Leave down comments if any doubts/suggestion.

Leave a Reply

Your email address will not be published. Required fields are marked *