Menu
Coddy logo textTech

Math - Set Difference

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

The difference between two sets results in a new set containing elements that are in the first set but not in the second. In Java, you can achieve this using the removeAll() method.

First, create two HashSets.
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);
set2.add(4);

Next, create a new HashSet for the difference - Start with all elements from set1:

HashSet<Integer> differenceSet = new HashSet<>(set1);

Then, remove all elements that appear in <strong>set2</strong>:

differenceSet.removeAll(set2); // [1]
challenge icon

Challenge

Easy

Create a method named <strong>setDifference</strong> that takes two HashSets of integers as input. The method should compute the difference (elements in the first set that are not in the second) and print the result in the format:

Difference: [elements]

Cheat sheet

The difference between two sets results in a new set containing elements that are in the first set but not in the second. Use the removeAll() method:

HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);

HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);
set2.add(4);

// Create difference set starting with all elements from set1
HashSet<Integer> differenceSet = new HashSet<>(set1);

// Remove all elements that appear in set2
differenceSet.removeAll(set2); // [1]

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 setDifference(HashSet<Integer> set1, HashSet<Integer> set2) {
        // Write your code here
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read JSON string representing the first set (e.g., [1,2,3])
        String set1String = scanner.nextLine();
        // Read JSON string representing the second set (e.g., [2,3,4])
        String set2String = scanner.nextLine();

        Type setType = new TypeToken<HashSet<Integer>>(){}.getType();
        HashSet<Integer> set1 = new Gson().fromJson(set1String, setType);
        HashSet<Integer> set2 = new Gson().fromJson(set2String, setType);

        setDifference(set1, set2);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow