What is the Deque.pollLast() method in Java?
In this shot, we will discuss how to use the Deque.pollLast() method, which is present in the Deque interface inside the java.util package.
The Deque.pollLast() method of Deque is used to retrieve and remove the last element of the given deque. If the given deque is empty, then this method will return null.
Syntax
Deque.PollLast();
Parameter
The Deque.pollLast() method does not take any parameter.
Return value
The Deque.pollLast() method returns the last element of the deque. It returns null if the deque is empty.
Code
Let’s illustrate the use of the Deque.pollLast() method with the help of 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.pollLast();System.out.println("first element of deque is:-\n"+ ele);System.out.println("deque after pollLast operation is:-\n"+ dq);}}
Explanation
- In line 1, we imported the
java.util.*package to include theDequeinterface. - In lines 7 to 17, we initialized the object of the deque of type
Integerand added elements10,20,30,40,and50in that. - In line 19, we printed the elements of the deque.
- In line 21, we used the method
deque.pollLast()and stored the returned element in theelevariable. - In the line 23, we printed the last element of deque.
- In line 25, we printed the deque after using the
pollLast()method.