The ArrayList.containsAll()
method in Java is used to check if the list contains all the elements present in a collection.
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.The ArrayList.containsAll()
method returns a boolean
, such that:
true
if the list contains all the elements present in the collection c
.false
if the list does not contain all the elements present in the collection c
.Note: If the collection is
null
, theArrayList.containsAll()
method throws theNullPointerException
.
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));}}
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
.
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));}}
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
.