What is ConcurrentLinkedDeque.removeFirstOccurrence() in Java?
The removeFirstOccurrence() method is used to remove the first occurrence of the specified element in the ConcurrentLinkedDeque object.
ConcurrentLinkedDequeis a thread-safe unbounded deque. Thenullvalue is not permitted as an element. We can useConcurrentLinkedDequewhen 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
ConcurrentLinkedDequeclass. -
Line 4: We created a
ConcurrentLinkedDequeobject with the namedeque. -
Lines 6 to 8: We used the
add()method of thedequeobject to add three elements, ("1","2","3"), todeque. -
Line 11: We used the
removeFirstOccurrence()method to remove the first occurrence of the element"1". The element"1"is present in two indexes,0and2. After calling this method, the element at index0will 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 returnsfalse.