Java program to check if a set is the subset of another set
Here's an example Java program to check if a set is a subset of another set:
import java.util.HashSet; import java.util.Set; public class SubsetChecker { public static void main(String[] args) { Set<Integer> set1 = new HashSet<>(); set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); Set<Integer> set2 = new HashSet<>(); set2.add(3); set2.add(4); if (isSubset(set2, set1)) { System.out.println("set2 is a subset of set1"); } else { System.out.println("set2 is not a subset of set1"); } } public static <T> boolean isSubset(Set<T> subset, Set<T> superset) { return superset.containsAll(subset); } }
This program uses an isSubset
method that takes two sets as input: a subset and a superset. The method returns true
if the subset is a subset of the superset, and false
otherwise.
To check if the subset is a subset of the superset, the isSubset
method uses the containsAll
method of the superset to check if it contains all elements of the subset. If the superset contains all elements of the subset, the method returns true
, indicating that the subset is a subset of the superset. If the superset does not contain all elements of the subset, the method returns false
, indicating that the subset is not a subset of the superset.
In the main method, two sets are created: set1
, which contains the numbers 1 to 5, and set2
, which contains the numbers 3 and 4. The isSubset
method is then called with set2
as the subset and set1
as the superset. If set2
is a subset of set1
, the program prints a message indicating that set2
is a subset of set1
. Otherwise, it prints a message indicating that set2
is not a subset of set1
.