What is the HashSet.containsAll() function in Java?

The containsAll() method of HashSet is used to check if the two sets contain similar elements or not.

Syntax

The syntax of the containsAll() function is shown below:

Hashset1.contains(Hashset2);

Parameter

The containsAll() method takes a single collection of sets as the parameter. The parameter is of the same type as the given HashSet.

We pass the set that needs to be checked if all the elements are the same or not.

Return

The method returns true if the second set contains all the same elements as present in the first set.

Code

Let’s take a look at the code now:

import java.util.*;
class Solution1{
public static void main(String args[])
{
// Creating an Empty HashSet
HashSet<String> set1 = new HashSet<String>();
// Use add() method
set1.add("Hello");
set1.add("I");
set1.add("love");
set1.add("Coding");
System.out.println("HashSet 1: "
+ set1);
HashSet<String> set2 = new HashSet<String>();
// Use add() method
set2.add("Hello");
set2.add("I");
set2.add("love");
set2.add("Coding");
System.out.println("HashSet 2: "
+ set2);
//use hashset.containsAll method
System.out.println("\nDoes set 1 contain set 2: "
+ set1.containsAll(set2));
}
}

Explanation:

  • In the first line of code, we have imported the java.util classes to include the HashSet Data structure.

  • In line 7, we have initiated an object set1 of empty HashSet of strings.

  • In lines 9 to 11, we have inserted some strings.

  • In line 13, we are printing the elements of set1.

  • From line 16 to 23, we have done the same thing by creating an object of HashSet of Strings, adding the same strings that were in set1, and displaying it.

  • In line 25, we are checking if both sets contain the same element or not by using the containAll() method.

So, in this way, we can use the hashset.containsAll() function in Java.

Free Resources