What is the ConcurrentLinkedQueue.removeAll() method in Java?
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
ConcurrentLinkedQueuewhen multiple threads are sharing a single Queue.
Syntax
boolean removeAll(Collection<?> c)
Argument
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.
Return Value
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.
Code
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);}}
Explanation
In the code above:
-
In line 1 and 2: We import the
ConcurrentLinkedQueueandArrayListclasses. -
From line 6-10: We create a new
ConcurrentLinkedQueueobject with the namequeueand add three elements (1,2,3) to thequeueobject using theadd()method. -
From line 12-15: We create a new
ArrayListobject with the namelistand add two elements (1,4) tolistobject using theadd()method. -
In line 21: We use the
removeAll()method to remove all the elements oflistfromqueue. The element1in the list is present inqueue, so it is removed. The element4is not present inqueue, so it is not removed. After calling theremoveAll()method, the content of thequeueobject changes, sotrueis returned.