Algorithm


Algorithm: IsSubset(set1, set2)
Input: Two sets, set1 and set2

1. Initialize a variable "isSubset" to true.
2. For each element in set1:
     a. If the element is not present in set2, set "isSubset" to false and break.
3. If step 2 completes without setting "isSubset" to false, then set1 is a subset of set2.
4. Output the value of "isSubset".

Code Examples

#1 Code Example- Check subset of a Set using HashSet class

Code - Java Programming

import java.util.HashSet;
import java.util.Set;

class Main {
  public static void main(String[] args) {

    // create the first set
    Set < Integer> numbers = new HashSet<>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    System.out.println("Numbers: " + numbers);

    // create the second set
    Set < Integer> primeNumbers = new HashSet<>();
    primeNumbers.add(2);
    primeNumbers.add(3);
    System.out.println("Prime Numbers: " + primeNumbers);

    // check if primeNumbers is a subset of numbers
    boolean result = numbers.containsAll(primeNumbers);
    System.out.println("Is Prime Numbers is subset of Numbers? " + result);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Numbers: [1, 2, 3, 4]
Prime Numbers: [2, 3]
Is Prime Numbers is subset of Numbers? true

#2 Code Example- Check subset of a Set using TreeSet class

Code - Java Programming

import java.util.TreeSet;
import java.util.Set;

class Main {
  public static void main(String[] args) {

    // create the first set
    Set < String> languages = new TreeSet<>();
    languages.add("Java");
    languages.add("JavaScript");
    languages.add("Python");
    languages.add("CSS");
    System.out.println("Programming Languages: " + languages);

    // create the second set
    Set < String> frontend = new TreeSet<>();
    frontend.add("CSS");
    frontend.add("JavaScript");
    System.out.println("Frontend Languages: " + frontend);

    // check if frontend is a subset of languages
    boolean result = languages.containsAll(frontend);
    System.out.println("Is frontend is subset of languages? " + result);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Programming Languages: [CSS, Java, JavaScript, Python]
Frontend Languages: [CSS, JavaScript]
Is frontend is subset of languages? true
Advertisements

Demonstration


Java Programing Example to Check if a set is the subset of another set-DevsEnv