Math - Union of HashSets
Part of the Logic & Flow section of Coddy's Java journey — lesson 29 of 59.
The union of two sets is a new set that contains every element that is in either set. In Java, you can compute the union of two HashSets using the addAll() method. This method adds all elements from one set into another (ignoring duplicates).
First, create a new two HashSets:
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);Use the addAll() method to add elements from the second set to your union set.
// First, create a new HashSet with set1
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2); // Then, add all elements from set2
System.out.println("Union: " + unionSet);
// Output: [1, 2, 3] (order may vary)Challenge
EasyCreate a method named <strong>unionSets</strong> that takes two HashSets of integers as input, computes their union, and prints it in the format:
Union: [1, 2, 3]
Cheat sheet
The union of two sets contains every element that is in either set. Use addAll() to compute the union of two HashSets:
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);
// Create union by copying first set and adding all elements from second
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
System.out.println("Union: " + unionSet);
// Output: [1, 2, 3] (order may vary)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 unionSets(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])
String set1String = scanner.nextLine();
// Read JSON string representing the second set (e.g., [2,3])
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);
unionSets(set1, set2);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap5HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceSubsets and SupersetsIterating Over Sets