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. Thenull
value is not permitted as an element. We can useConcurrentLinkedDeque
when multiple threads are sharing a single Deque.
public boolean removeFirstOccurrence(Object o)
This method takes the element to be removed from the deque
as a parameter.
This method returns true
if the deque
contains the specified element. Otherwise, false
is returned.
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);}}
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
.