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

Overview

The Deque.removeFirst() method is present in the Deque interface inside the java.util package.

Deque.removeFirst() is used to remove the element from the front of the deque.

Syntax

boolean removeFirst(element)

Parameters

The Deque.removeFirst() method doesn’t take any parameters.

Return value

The Deque.removeFirst() method returns a boolean value:

  • True: The element is successfully removed from the front of the deque.
  • False: The element is not successfully removed from the front of the deque.

Example

Let us take 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);
d.removeFirst();
d.removeFirst();
System.out.println("Elements in the deque are: "+d);
}
}

Code 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 deque that consists of Integer type elements.

  • Lines 8 - 14: We use the Deque.add() method to insert the elements in the deque.

  • Lines 16 and 17: We use the removeFirst() method to remove the elements from the front of the deque.

  • Line 21: We display the deque elements.

Note: The first two elements have been removed.

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

Free Resources