What is Deque.poll() method in Java?
Overview
Deque.poll() method is present in the Deque interface inside the java.util package. It is used to retrieve and remove the head element of the given Deque. If the given Deque is empty, then this method returns null.
Syntax
Let’s view the syntax of the function Dequeue.poll():
Deque.poll();
Parameter
Deque.poll() method doesn’t take any parameter.
Return value
Deque.poll() method returns the first element of deque. On the other hand, returns null if the deque is empty.
Code
Let us look at the code snippet below:
import java.util.*;class Solution {public static void main(String[] args) {Deque<Integer> dq= new ArrayDeque<>();dq.add(10);dq.add(20);dq.add(30);dq.add(40);dq.add(50);System.out.println("the elements of deque are:-\n"+dq);int ele= dq.poll();System.out.println("first element of deque is:-\n"+ ele);System.out.println("deque after poll operation is:-\n"+ dq);}}
Explanation
- In line 1, we have imported the
java.util.*package to include the Deque interface. - In line 6 to 10, we have initialized the object of deque of
Integertype and, added elements 10,20,30,40,50 in that. - In line 11, we are printing the elements of deque.
- In line 12, we are using the method
deque.poll()and storing the returned element in ele variable. - In line 13, we are printing the head of deque.
- In line 14, printing the deque after using
poll()method.
In this way, we can use Deque.poll() method in Java.