What is the Deque.pop() method in Java?

In this shot, we will discuss the Deque.pop() method in Java. The Deque.pop() method is present in the Deque interface inside the java.util package. Deque.pop() is used to remove the element from the top of the deque.

Syntax

void deque.pop()

Parameter

The Deque.pop() method does not take any parameters.

Return

The Deque.pop() method returns the element which is being removed and is present at the head of the deque.

Code

Let’s have a look at the code snippet below:

import java.util.*;
class Main
{
public static void main(String[] args)
{
Deque<Integer> d = new LinkedList<Integer>();
d.add(212);
d.add(23);
d.add(621);
d.add(1280);
d.add(3121);
d.add(18297);
d.add(791);
System.out.println("Element popped: "+d.pop());
System.out.println("Element popped: "+d.pop());
System.out.println("Elements in the deque are: "+d);
}
}

Explanation

  • In line 1, we import the required package.
  • In line 2, we make a Main class.
  • In line 4, we make a main function.
  • In line 6, we declare a deque consisting of Integer type elements.
  • From lines 8 to 14, we insert the elements in the deque by using the Deque.add() method.
  • In line 16 and 17, we remove the head element from the deque by using the Deque.pop() method and display the popped element.
  • In line 19, we display the deque elements.

In this way, we can use the Deque.pop() method in Java.

Free Resources