What is ConcurrentLinkedDeque.removeFirstOccurrence() in Java?

The removeFirstOccurrence() method is used to remove the first occurrence of the specified element in the ConcurrentLinkedDeque object.

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

Syntax


public boolean removeFirstOccurrence(Object o)

Parameters

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

Return values

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

Code

The code below demonstrates how to use the removeFirstOccurrence() method.

import java.util.concurrent.ConcurrentLinkedDeque;
class RemoveFirstOccurrence {
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 1 present & removed: " + deque.removeFirstOccurrence("1"));
System.out.println("The deque is " + deque);
System.out.println("Is element 4 present & removed: " + deque.removeFirstOccurrence("1"));
System.out.println("The deque is " + deque);
}
}

Explanation

In the code above:

  • Line 1: We imported the ConcurrentLinkedDeque class.

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

  • Lines 6 to 8: We used the add() method of the deque object to add three elements, ("1","2","3"), to deque.

  • Line 11: We used the removeFirstOccurrence() method to remove the first occurrence of the element "1". The element "1" is present in two indexes, 0 and 2. After calling this method, the element at index 0 will be removed.

  • Line 15: We used the removeFirstOccurrence() method to remove the first occurrence of the element "4".

    The element "4" is not present. Therefore, this method returns false.

Free Resources