The removeAll()
method will remove all the elements of the passed collection from the ConcurrentLinkedQueue
if present.
The ConcurrentLinkedQueue
is thread-safe unbounded queue. The elements are ordered by FIFO(First-In-First-Out). The elements are inserted at the tail (end) and retrieved from the head (start) of the queue. The null
elements are not allowed as an element of the queue.
Note: We can use the
ConcurrentLinkedQueue
when multiple threads are sharing a single Queue.
boolean removeAll(Collection<?> c)
This method takes the collection object to be removed from the queue
as an argument.
The NullPointerException
is thrown if the passed collection contains a null
element.
This method returns true
if the queue
changed as a result of the call (any one of the elements from the Collection
is present and removed from the queue
). Otherwise, false
will be returned.
The code below demonstrates how to use the removeAll()
method:
import java.util.concurrent.ConcurrentLinkedQueue;import java.util.ArrayList;class RemoveAll {public static void main( String args[] ) {// create a new queu which can have integer elementsConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();// add elements to the queuequeue.add(1);queue.add(2);queue.add(3);// create a new array listArrayList<Integer> list = new ArrayList<>();// add some elements to itlist.add(1);list.add(4);System.out.println("The queue is "+ queue);System.out.println("The list is "+ list);//remove all the elements of the list from the queueSystem.out.println("\nCalling queue.removeAll(list). Is queue changed - " + queue.removeAll(list));System.out.println("\nThe queue is "+ queue);}}
In the code above:
In line 1 and 2: We import the ConcurrentLinkedQueue
and ArrayList
classes.
From line 6-10: We create a new ConcurrentLinkedQueue
object with the name queue
and add three elements (1
,2
,3
) to the queue
object using the add()
method.
From line 12-15: We create a new ArrayList
object with the name list
and add two elements (1
,4
) to list
object using the add()
method.
In line 21: We use the removeAll()
method to remove all the elements of list
from queue
. The element 1
in the list is present in queue
, so it is removed. The element 4
is not present in queue
, so it is not removed. After calling the removeAll()
method, the content of the queue
object changes, so true
is returned.