Write a Java Program to Check if a set is the subset of another set

In Java, we can use the built-in Set interface to check if a set is a subset of another set.

The Set interface provides several methods to perform set operations like union, intersection, and subset.


We can use the subset method to determine if a set is a subset of another set.

Here is an example Java program that checks if a set is a subset of another set:

import java.util.*;

public class SetSubsetExample {
    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
        Set<Integer> set2 = new HashSet<>(Arrays.asList(2, 4));

        boolean isSubset = set1.containsAll(set2);

        if (isSubset) {
            System.out.println("set2 is a subset of set1");
        } else {
            System.out.println("set2 is not a subset of set1");
        }
    }
}

In this example, we create two sets using the HashSet class and add elements to them using the Arrays.asList method.

Then, we use the containsAll method of the set1 object to check if all elements of set2 are present in set1.

If the containsAll method returns true, it means set2 is a subset of set1.

We can modify this program to take user input for the sets and make it more interactive.

Here is an example program that takes user input for the two sets:

import java.util.*;

public class SetSubsetExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the elements of set1 separated by commas:");
        String[] set1Array = sc.nextLine().split(",");
        Set<Integer> set1 = new HashSet<>();
        for (String s : set1Array) {
            set1.add(Integer.parseInt(s.trim()));
        }

        System.out.println("Enter the elements of set2 separated by commas:");
        String[] set2Array = sc.nextLine().split(",");
        Set<Integer> set2 = new HashSet<>();
        for (String s : set2Array) {
            set2.add(Integer.parseInt(s.trim()));
        }

        boolean isSubset = set1.containsAll(set2);

        if (isSubset) {
            System.out.println("set2 is a subset of set1");
        } else {
            System.out.println("set2 is not a subset of set1");
        }
    }
}

In this program, we use the Scanner class to read user input for the two sets.

We split the input string using the comma separator and add each element to the respective set using the parseInt method to convert the string to an integer.

We can use this program to check if any set is a subset of another set by modifying the input prompts and variable names.


In conclusion, we can use the Set interface in Java to check if a set is a subset of another set using the containsAll method.

We can make the program more interactive by taking user input for the sets.