Math - Intersection of HashSet
Part of the Logic & Flow section of Coddy's Java journey — lesson 30 of 59.
The intersection of two sets is a new set that contains only the elements that are present in both sets. In Java, you can compute the intersection by using the retainAll() method.
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);This new set will start with all elements from the first set.
HashSet<Integer> intersectionSet = new HashSet<>(set1);Next, retain only the elements that are also in the second set:
Use the retainAll() method.
intersectionSet.retainAll(set2);
System.out.println("Intersection: " +
intersectionSet);
// Output: [2]Challenge
EasyCreate a method named <strong>intersectionSets</strong> that takes two HashSets of integers as input, computes their intersection, and prints it in the format:
Intersection: [2]
Cheat sheet
The intersection of two sets contains only elements present in both sets. Use retainAll() to compute intersection:
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);
// Create new set with elements from first set
HashSet<Integer> intersectionSet = new HashSet<>(set1);
// Retain only elements that are also in second set
intersectionSet.retainAll(set2);
System.out.println("Intersection: " + intersectionSet);
// Output: [2]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 intersectionSets(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])
String set1String = scanner.nextLine();
// Read JSON string for 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);
intersectionSets(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