Set containsAll() Method in Java
Last Updated :
05 Feb, 2025
Improve
The containsAll() method of Set in Java is used to check if a collection contains all the elements of a specified collection. This method is part of the Collection interface.
Example 1: This example checks if all elements of one set are present in another set and it will return true if they are identical.
// Java program to demonstrates
// the working of containsAll() method
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Creating an empty set
Set<String> s1 = new HashSet<String>();
// Use add() method to
// add elements in the set
s1.add("Java");
s1.add("C++");
s1.add("Python");
System.out.println("Set 1: " + s1);
// Creating another empty set
Set<String> s2 = new HashSet<String>();
// Use add() method to
// add elements in the set
s2.add("Java");
s2.add("C++");
s2.add("Python");
System.out.println("Set 2: " + s2);
// Check if the set
// contains same elements
System.out.println("Does set 1 contains set 2?: "
+ s1.containsAll(s2));
}
}
Output
Set 1: [Java, C++, Python] Set 2: [Java, C++, Python] Does set 1 contains set 2?: true
Syntax of containsAll() Method
boolean containsAll(Collection<?> c)
- Parameter: "c" is the collection whose elements are to be checked in the current collection.
- Return Type: This method returns "true" if the current collection contains all the elements of the specified collection, otherwise returns "false".
Example 2: This example checks if all elements of one set are present in another set and it will return false if they are not identical.
// Java program to demonstrates that
// containsALl() method returns false
import java.util.*;
class Geeks {
public static void main(String args[]) {
// Creating an empty s1
Set<String> s1 = new HashSet<String>();
// Use add() method to add elements in s1
s1.add("Java");
s1.add("C++");
s1.add("Python");
System.out.println("Set 1: " + s1);
// Creating another empty s2
Set<String> s2 = new HashSet<String>();
// Use add() method to add elements in s2
s2.add("10");
s2.add("20");
System.out.println("Set 2: " + s2);
// Check if s1 contains all elements of s2
System.out.println("Does s1 contain all elements of s2: "
+ s1.containsAll(s2));
}
}
Output
Set 1: [Java, C++, Python] Set 2: [20, 10] Does s1 contain all elements of s2: false