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

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Check subset of a Set using HashSet class

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);
  }
}

Output

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

In the above example, we have created two sets named numbers and primeNumbers. We have implemented the set using the HashSet class. Notice the line,

numbers.containsAll(primeNumbers);

Here, we have used the containsAll() method to check if primeNumbers is the subset of numbers.


Example 2: Check subset of a Set using TreeSet class

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);
  }
}

Output

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

Here, we have implemented the set using the TreeSet class.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges