Menu
Coddy logo textTech

Subsets and Supersets

Part of the Logic & Flow section of Coddy's Java journey — lesson 33 of 59.

A subset is a set in which every element is also contained in another set. A superset is a set that contains all the elements of another set.

First, create two HashSets:

HashSet<String> setA = new HashSet<>();
setA.add("apple");
setA.add("banana");
HashSet<String> setB = new HashSet<>();
setB.add("apple");
setB.add("banana");
setB.add("cherry");

Use the containsAll() method:

boolean isSubset = setB.containsAll(setA);
System.out.println("setA is a subset of setB: " + isSubset);
// Output: setA is a subset of setB: true

Similarly, setB is a superset of setA because it contains every element of setA.

challenge icon

Challenge

Easy

Create a method named <strong>checkSubsetSuperset</strong> that takes two HashSets of strings as input:

  • setA and setB

The method should:

  1. Check if setA is a subset of setB using containsAll(), and print:

    setA is a subset of setB: <true/false>
  2. Check if setB is a superset of setA (this is the same check), and print:

    setB is a superset of setA: <true/false>

Cheat sheet

A subset is a set in which every element is also contained in another set. A superset is a set that contains all the elements of another set.

Use the containsAll() method to check if one set is a subset of another:

HashSet<String> setA = new HashSet<>();
setA.add("apple");
setA.add("banana");

HashSet<String> setB = new HashSet<>();
setB.add("apple");
setB.add("banana");
setB.add("cherry");

boolean isSubset = setB.containsAll(setA);
System.out.println("setA is a subset of setB: " + isSubset);
// Output: setA is a subset of setB: true

If setA is a subset of setB, then setB is a superset of setA.

Try it yourself

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void checkSubsetSuperset(HashSet<String> setA, HashSet<String> setB) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read JSON string for setA (e.g., ["apple","banana"])
        String setAString = scanner.nextLine();
        // Read JSON string for setB (e.g., ["apple","banana","cherry"])
        String setBString = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> setA = new Gson().fromJson(setAString, setType);
        HashSet<String> setB = new Gson().fromJson(setBString, setType);
        
        checkSubsetSuperset(setA, setB);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow