What is the ArrayDeque.removeLastOccurrence method in Java?

An ArrayDequeArray Double Ended Queue is a growable array that allows us to add or remove an element from both the front and back. This class is the implementation class of the Deque interface.

ArrayDeque can be used as both a stack or queue. Null elements are prohibited.

What is the removeLastOccurrence method?

The removeLastOccurrence method of the ArrayDeque class is used to remove the last occurrence of the specified element in the ArrayDeque object.

Syntax

public boolean removeLastOccurrence(Object o)

Parameter

This method takes the element to be removed from the deque as a parameter.

Return value

This method returns true if the deque contains the specified element. Otherwise, it returns false.

Code

The code below demonstrates how to use the removeLastOccurrence method.

import java.util.ArrayDeque;
class ArrayDequeRemoveLastOccurrenceExample {
public static void main( String args[] ) {
ArrayDeque<String> arrayDeque = new ArrayDeque<>();
arrayDeque.add("1");
arrayDeque.add("2");
arrayDeque.add("1");
System.out.println("The arrayDeque is " + arrayDeque);
System.out.println("Is element present & removed: " + arrayDeque.removeLastOccurrence("1"));
System.out.println("The arrayDeque is " + arrayDeque);
}
}

Explanation

In the code above:

  • In line 1, we imported the ArrayDeque class.

  • In line 4, we created an ArrayDeque object with the name arrayDeque.

  • From lines 5 to 7, we used the add() method of the arrayDeque object to add three elements ("1","2","3") to deque.

  • In line 10, we used the removeLastOccurrence method to remove the last occurrence of the element "1". The element "1" is present in two indexes 0 and 2. After calling this method, the element at index 2 will be removed.