What is the ConcurrentLinkedQueue.containsAll() method in Java?
Introduction
The containsAll() method in Java checks if all elements of the specific collection object are present in the ConcurrentLinkedQueue object.
ConcurrentLinkedQueueis a thread-safe, unbounded queue.
The elements are ordered by First-In-First-Out (FIFO). The elements are inserted at the tail (end) and retrieved from the head (start) of the queue.
null elements are not allowed as elements of the queue.
We use ConcurrentLinkedQueue when multiple threads share a single queue.
Syntax
public boolean containsAll(Collection<?> c)
Parameters
The argument is the collection that we check for in the queue.
Return value
The containsAll() method returns true if all the elements of the passed collection are present in the queue.
Code
The code below demonstrates how to use the containsAll() method.
import java.util.concurrent.ConcurrentLinkedQueue;import java.util.ArrayList;class containsAll {public static void main( String args[] ) {ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();queue.add(1);queue.add(2);queue.add(3);ArrayList<Integer> list1 = new ArrayList<>();list1.add(1);list1.add(3);System.out.println("The queue is "+ queue);System.out.println("\nlist1 is "+ list1);System.out.println("If queue contains all elements of list1 : "+ queue.containsAll(list1));ArrayList<Integer> list2 = new ArrayList<>();list2.add(4);System.out.println("\nlist2 is "+ list2);System.out.println("If queue contains all elements of list2 : "+ queue.containsAll(list2));}}
Explanation
-
Lines 1 to 2: We import the
ConcurrentLinkedQueueandArrayListclasses. -
Line 4: We create an object named
queuefor theConcurrentLinkedQueueclass. -
Lines 6 to 8: We add three elements (
1,2,3) to the createdqueueobject. -
Line 10: We create a new
ArrayListobject namedlist1and add the elements (1,3) to it. -
Line 16: We call the
containsAll()method to check if all the elements oflist1are present inqueue. In this case, the condition returnstruebecause all the elements (1,3) oflist1are present inqueue. -
Line 18: We create a new
ArrayListobject namedlist2and add the element4to it. -
Line 22: We call the
containsAll()method again to check if all elements oflist2are present inqueue. In this case, the condition returnsfalse. This is because element4oflist2is not present inqueue.