What is ConcurrentLinkedDeque.removeLastOccurrence() in Java?

ConcurrentLinkedDeque is a thread-safe, unbounded deque. The null value is not permitted as an element. We can use ConcurrentLinkedDeque when multiple threads share a single deque.

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

Syntax

public boolean removeLastOccurrence(Object o)

Parameters

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

Return value

The removeLastOccurrence 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.concurrent.ConcurrentLinkedDeque;
class RemoveLastOccurrence {
public static void main( String args[] ) {
ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();
deque.add("1");
deque.add("2");
deque.add("1");
System.out.println("The deque is " + deque);
System.out.println("Is element present & removed: " + deque.removeLastOccurrence("1"));
System.out.println("The deque is " + deque);
}
}

Explanation

In the code above:

  • Line 1: We import the ConcurrentLinkedDeque class.

  • Line 4: We create a ConcurrentLinkedDeque object with the name deque.

  • Lines 5-7: We use the add() method of the deque object to add three elements ("1","2","3") to the deque.

  • Line 10: We use the removeLastOccurrence method to remove the last occurrence of the element "1". The element "1" is present at two indexes, 0 and 2. After we call this method, the element at index 2 will be removed.

Free Resources