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.

ConcurrentLinkedQueue is 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 ConcurrentLinkedQueue and ArrayList classes.

  • Line 4: We create an object named queue for the ConcurrentLinkedQueue class.

  • Lines 6 to 8: We add three elements (1,2,3) to the created queue object.

  • Line 10: We create a new ArrayList object named list1 and add the elements (1,3) to it.

  • Line 16: We call the containsAll() method to check if all the elements of list1 are present in queue. In this case, the condition returns true because all the elements (1,3) of list1 are present in queue.

  • Line 18: We create a new ArrayList object named list2 and add the element 4 to it.

  • Line 22: We call the containsAll() method again to check if all elements of list2 are present in queue. In this case, the condition returns false. This is because element 4 of list2 is not present in queue.

Free Resources