List containsAll() method in Java with Examples
Last Updated :
11 Dec, 2018
The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection. So basically it is used to check if a List contains a set of elements or not.
Syntax:
boolean containsAll(Collection col)
Parameters: This method accepts a mandatory parameter col which is of the type of collection. This is the collection whose elements are needed to be checked if it is present in the List or not.
Return Value: The method returns True if all elements in the collection col are present in the List otherwise it returns False.
Exception: The method throws NullPointerException if the specified collection is NULL.
Below programs illustrates the containsAll() method:
Program 1:
import java.util.*;
public class ListDemo {
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add( "Welcome" );
list.add( "To" );
list.add( "Geeks" );
list.add( "4" );
list.add( "Geeks" );
System.out.println( "List: " + list);
List<String> listTemp = new ArrayList<String>();
listTemp.add( "Geeks" );
listTemp.add( "4" );
listTemp.add( "Geeks" );
System.out.println( "Are all the contents equal? "
+ list.containsAll(listTemp));
}
}
|
Output:
List: [Welcome, To, Geeks, 4, Geeks]
Are all the contents equal? true
Program 2:
import java.util.*;
public class ListDemo {
public static void main(String args[])
{
List<Integer> list = new ArrayList<Integer>();
list.add( 10 );
list.add( 15 );
list.add( 30 );
list.add( 20 );
list.add( 5 );
System.out.println( "List: " + list);
List<Integer> listTemp = new ArrayList<Integer>();
listTemp.add( 30 );
listTemp.add( 15 );
listTemp.add( 5 );
System.out.println( "Are all the contents equal? "
+ list.containsAll(listTemp));
}
}
|
Output:
List: [10, 15, 30, 20, 5]
Are all the contents equal? true
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#containsAll(java.util.Collection)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...