What is the ArrayList.containsAll() method in Java?
The ArrayList.containsAll() method in Java is used to check if the list contains all the elements present in a collection.
Syntax
The ArrayList.containsAll() method in Java can be declared as shown in the code snippet below:
boolean containsAll(Collection c)
c: The collection whose elements will be checked if they are present in the list.
Return value
The ArrayList.containsAll() method returns a boolean, such that:
- The return value is
trueif the list contains all the elements present in the collectionc. - The return value is
falseif the list does not contain all the elements present in the collectionc.
Note: If the collection is
null, theArrayList.containsAll()method throws theNullPointerException.
Examples
Example 1
Consider the code snippet below, which demonstrates the use of the ArrayList.containsAll() method.
import java.util.*;public class Example1 {public static void main(String args[]){List<String> list1 = new ArrayList<String>();list1.add("Hello");list1.add("world");list1.add("!");System.out.println("list1: " + list1);List<String> list2 = new ArrayList<String>();list2.add("Hello");list2.add("world2");System.out.println("list2: " + list2);System.out.println("list1.containsAll(): " + list1.containsAll(list2));}}
Explanation
Two lists, list1 and list2, are declared in line 7 and line 13 respectively. The ArrayList.containsAll() method is used in line 18 to check if all the elements of list2 are present in list1. The ArrayList.containsAll() method returns false, which means that list1 does not contain all the elements in list2.
Example 2
Consider another example of the ArrayList.containsAll() method.
import java.util.*;public class Example2 {public static void main(String args[]){List<String> list1 = new ArrayList<String>();list1.add("Hello");list1.add("world");list1.add("!");System.out.println("list1: " + list1);List<String> list2 = new ArrayList<String>();list2.add("Hello");list2.add("world");System.out.println("list2: " + list2);System.out.println("list1.containsAll(): " + list1.containsAll(list2));}}
Explanation
Two lists, list1 and list2, are declared in line 7 and line 13 respectively. The ArrayList.containsAll() method is used in line 18 to check if all the elements of list2 are present in list1. The ArrayList.containsAll() method returns true, which means that list1 contains all the elements in list2.