Use containsAll() for Subset Check
In this step, we will explore how to check if one set is a subset of another using the containsAll() method in Java. This is a common operation when working with collections, and containsAll() provides a convenient way to perform this check.
First, let's create a new Java file named SubsetCheck.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing SubsetCheck.java.
Now, open the SubsetCheck.java file in the editor and add the following code:
import java.util.HashSet;
import java.util.Set;
public class SubsetCheck {
public static void main(String[] args) {
// Create the main set
Set<Integer> mainSet = new HashSet<>();
mainSet.add(1);
mainSet.add(2);
mainSet.add(3);
mainSet.add(4);
mainSet.add(5);
// Create a potential subset
Set<Integer> subset = new HashSet<>();
subset.add(2);
subset.add(4);
// Check if 'subset' is a subset of 'mainSet'
boolean isSubset = mainSet.containsAll(subset);
// Print the result
System.out.println("Main Set: " + mainSet);
System.out.println("Subset: " + subset);
System.out.println("Is 'subset' a subset of 'mainSet'? " + isSubset);
}
}
Let's break down the code:
import java.util.HashSet; and import java.util.Set;: These lines import the necessary classes for working with sets.
Set<Integer> mainSet = new HashSet<>();: This creates a HashSet named mainSet that will store integer values.
mainSet.add(...): These lines add elements to the mainSet.
Set<Integer> subset = new HashSet<>();: This creates another HashSet named subset.
subset.add(...): These lines add elements to the subset.
boolean isSubset = mainSet.containsAll(subset);: This is the core of this step. The containsAll() method of the mainSet is called with subset as an argument. It returns true if mainSet contains all the elements of subset, and false otherwise.
System.out.println(...): These lines print the sets and the result of the subset check to the console.
Save the SubsetCheck.java file (Ctrl+S or Cmd+S).
Now, open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory. If not, use the command cd ~/project.
Compile the Java code using the javac command:
javac SubsetCheck.java
If there are no errors, you should see no output. This means the compilation was successful and a SubsetCheck.class file has been created.
Finally, run the compiled Java program using the java command:
java SubsetCheck
You should see output similar to this:
Main Set: [1, 2, 3, 4, 5]
Subset: [2, 4]
Is 'subset' a subset of 'mainSet'? true
This output confirms that the containsAll() method correctly identified that subset is indeed a subset of mainSet.