Menu
Coddy logo textTech

Math - Symmetric Difference

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

The symmetric difference of two sets is a new set that contains elements that are in either set but not in both. In Java, you can compute it by:

  1. Finding the difference of the first set with respect to the second.
  1. Finding the difference of the second set with respect to the first.
  1. Combining these two differences.

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, remove the same values:

HashSet<Integer> diff1 = new HashSet<>(set1);
diff1.removeAll(set2);  // diff1 is [1]
HashSet<Integer> diff2 = new HashSet<>(set2);
diff2.removeAll(set1);  // diff2 is [4]

Next, remove the two differences:

diff1.addAll(diff2);  // diff1 is 1, 4]
challenge icon

Challenge

Easy

Create a method named <strong>symmetricDifference</strong> that takes two HashSets of integers as input, computes their symmetric difference, and prints it in the format:

Symmetric Difference: [elements]

Cheat sheet

The symmetric difference of two sets contains elements that are in either set but not in both.

To compute symmetric difference in Java:

  1. Find the difference of the first set with respect to the second
  2. Find the difference of the second set with respect to the first
  3. Combine these two differences
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);

// Remove common elements from each set
HashSet<Integer> diff1 = new HashSet<>(set1);
diff1.removeAll(set2);  // diff1 is [1]

HashSet<Integer> diff2 = new HashSet<>(set2);
diff2.removeAll(set1);  // diff2 is [4]

// Combine the differences
diff1.addAll(diff2);  // diff1 is [1, 4]

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 symmetricDifference(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 for the first set (e.g., [1,2,3])
        String set1String = scanner.nextLine();
        // Read JSON string for 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);

        symmetricDifference(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