Introduction
In this lab, you will learn how to check if one set contains all elements of another set in Java. We will explore the containsAll() method, a convenient way to perform this subset check.
Through hands-on examples, you will learn how to use containsAll() with different set types and how to handle edge cases like empty and null sets.
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;andimport java.util.Set;: These lines import the necessary classes for working with sets.Set<Integer> mainSet = new HashSet<>();: This creates aHashSetnamedmainSetthat will store integer values.mainSet.add(...): These lines add elements to themainSet.Set<Integer> subset = new HashSet<>();: This creates anotherHashSetnamedsubset.subset.add(...): These lines add elements to thesubset.boolean isSubset = mainSet.containsAll(subset);: This is the core of this step. ThecontainsAll()method of themainSetis called withsubsetas an argument. It returnstrueifmainSetcontains all the elements ofsubset, andfalseotherwise.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.
Test with Different Set Types
In the previous step, we used HashSet to demonstrate the containsAll() method. Java provides different implementations of the Set interface, such as HashSet, LinkedHashSet, and TreeSet. While they have different internal structures and properties (like order), the containsAll() method works consistently across them.
In this step, we will modify our SubsetCheck.java file to test containsAll() with different types of sets.
Open the SubsetCheck.java file in the WebIDE editor.
Replace the existing code with the following:
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class SubsetCheck {
public static void main(String[] args) {
// Create a main set using HashSet
Set<Integer> hashMainSet = new HashSet<>();
hashMainSet.add(10);
hashMainSet.add(20);
hashMainSet.add(30);
hashMainSet.add(40);
// Create a subset using LinkedHashSet
Set<Integer> linkedSubset = new LinkedHashSet<>();
linkedSubset.add(30);
linkedSubset.add(10);
// Create another subset using TreeSet
Set<Integer> treeSubset = new TreeSet<>();
treeSubset.add(40);
treeSubset.add(20);
// Check subset relationship using containsAll()
boolean isLinkedSubset = hashMainSet.containsAll(linkedSubset);
boolean isTreeSubset = hashMainSet.containsAll(treeSubset);
// Create a subset that is NOT a subset
Set<Integer> notSubset = new HashSet<>();
notSubset.add(20);
notSubset.add(50); // 50 is not in hashMainSet
boolean isNotSubset = hashMainSet.containsAll(notSubset);
// Print the results
System.out.println("Hash Main Set: " + hashMainSet);
System.out.println("Linked Subset: " + linkedSubset);
System.out.println("Is Linked Subset a subset of Hash Main Set? " + isLinkedSubset);
System.out.println("Tree Subset: " + treeSubset);
System.out.println("Is Tree Subset a subset of Hash Main Set? " + isTreeSubset);
System.out.println("Not Subset: " + notSubset);
System.out.println("Is Not Subset a subset of Hash Main Set? " + isNotSubset);
}
}
In this updated code:
- We've imported
LinkedHashSetandTreeSet. - We created a
hashMainSetusingHashSet. - We created
linkedSubsetusingLinkedHashSetandtreeSubsetusingTreeSet. Notice that the order of elements added tolinkedSubsetis different from how they appear inhashMainSet, butcontainsAll()still works correctly.TreeSetautomatically sorts elements. - We also added a
notSubsetto demonstrate a case wherecontainsAll()returnsfalse.
Save the SubsetCheck.java file.
Now, compile the modified code in the Terminal:
javac SubsetCheck.java
If the compilation is successful, run the program:
java SubsetCheck
You should see output similar to this:
Hash Main Set: [40, 10, 20, 30]
Linked Subset: [30, 10]
Is Linked Subset a subset of Hash Main Set? true
Tree Subset: [20, 40]
Is Tree Subset a subset of Hash Main Set? true
Not Subset: [50, 20]
Is Not Subset a subset of Hash Main Set? false
This demonstrates that containsAll() works correctly regardless of the specific Set implementation used for the subset, as long as the main set contains all the elements of the subset.
Handle Empty and Null Sets
In this final step, we will examine how the containsAll() method behaves when dealing with empty sets and null values. Understanding these edge cases is important for writing robust code.
Open the SubsetCheck.java file in the WebIDE editor.
Replace the existing code with the following:
import java.util.HashSet;
import java.util.Set;
public class SubsetCheck {
public static void main(String[] args) {
Set<Integer> mainSet = new HashSet<>();
mainSet.add(1);
mainSet.add(2);
mainSet.add(3);
// Case 1: Checking with an empty set
Set<Integer> emptySet = new HashSet<>();
boolean isEmptySubset = mainSet.containsAll(emptySet);
System.out.println("Main Set: " + mainSet);
System.out.println("Empty Set: " + emptySet);
System.out.println("Is Empty Set a subset of Main Set? " + isEmptySubset);
System.out.println("---"); // Separator
// Case 2: Checking if an empty set contains all elements of a non-empty set
Set<Integer> anotherEmptySet = new HashSet<>();
Set<Integer> nonEmptySet = new HashSet<>();
nonEmptySet.add(1);
boolean isEmptyContainingNonEmpty = anotherEmptySet.containsAll(nonEmptySet);
System.out.println("Another Empty Set: " + anotherEmptySet);
System.out.println("Non-Empty Set: " + nonEmptySet);
System.out.println("Is Another Empty Set a subset of Non-Empty Set? " + isEmptyContainingNonEmpty);
System.out.println("---"); // Separator
// Case 3: Checking with a null set
Set<Integer> nullSet = null;
try {
boolean isNullSubset = mainSet.containsAll(nullSet);
System.out.println("Is Null Set a subset of Main Set? " + isNullSubset);
} catch (NullPointerException e) {
System.out.println("Checking with a null set resulted in a: " + e.getClass().getName());
}
}
}
Let's look at the new parts:
- Case 1: Checking with an empty set: We create an
emptySetand check ifmainSetcontains all its elements. An empty set is considered a subset of any set, including another empty set. - Case 2: Checking if an empty set contains all elements of a non-empty set: We check if
anotherEmptySetcontains all elements ofnonEmptySet. This should be false because the empty set does not contain the element1. - Case 3: Checking with a null set: We set a
Setvariable tonull. Attempting to callcontainsAll()with anullargument will result in aNullPointerException. We use atry-catchblock to handle this expected exception gracefully and print a message.
Save the SubsetCheck.java file.
Compile the code in the Terminal:
javac SubsetCheck.java
Run the compiled program:
java SubsetCheck
You should see output similar to this:
Main Set: [1, 2, 3]
Empty Set: []
Is Empty Set a subset of Main Set? true
---
Another Empty Set: []
Non-Empty Set: [1]
Is Another Empty Set a subset of Non-Empty Set? false
---
Checking with a null set resulted in a: java.lang.NullPointerException
This output confirms the behavior of containsAll() with empty and null sets:
- An empty set is always a subset of another set (
true). - A non-empty set is never a subset of an empty set (
false). - Passing
nulltocontainsAll()results in aNullPointerException.
Understanding these cases helps you avoid potential errors when working with sets in Java.
Summary
In this lab, we learned how to check if one set contains all elements of another set in Java using the containsAll() method. We started by creating a basic example using HashSet to demonstrate the core functionality of containsAll(). This method provides a straightforward way to determine if a potential subset is indeed contained within a larger set.
We then explored how to test this functionality with different types of sets, understanding that containsAll() works consistently across various Set implementations. Finally, we addressed the important considerations of handling empty and null sets when performing subset checks, ensuring robust and error-free code.



