Calculating the intersection of two sets is a common operation in programming, particularly in Java.
In this tutorial, we will explore how to write a Java program to calculate the intersection of two sets.
In Java, we can use the built-in HashSet class to represent a set.
A HashSet is an implementation of the Set interface that uses a hash table for storage.
HashSet provides constant-time performance for the basic operations, such as add, remove, contains, and size, assuming that the hash function disperses the elements properly among the buckets.
To calculate the intersection of two sets using HashSet, we first create two HashSet objects, one for each set.
We then use the retainAll() method of the first set and pass the second set as a parameter.
This method modifies the first set to contain only the elements that are also contained in the second set, which is the intersection of the two sets.
Here’s an example Java program that calculates the intersection of two sets using HashSet:
import java.util.*;
public class SetIntersectionExample {
public static void main(String[] args) {
// create the first set
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
// create the second set
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
// calculate the intersection
set1.retainAll(set2);
// print the intersection
System.out.println("Intersection of Set 1 and Set 2: " + set1);
}
}In this program, we create two sets, set1 and set2, and initialize them with some values using the Arrays.asList() method.
We then calculate the intersection of the two sets by calling the retainAll() method on set1 and passing set2 as a parameter.
Finally, we print the intersection using the System.out.println() method.
When we run this program, the output will be:
Intersection of Set 1 and Set 2: [3, 4, 5]
This output shows that the intersection of set1 and set2 is {3, 4, 5}.
In conclusion, calculating the intersection of two sets in Java is a simple process that can be accomplished using the HashSet class and the retainAll() method.
By using these tools, we can quickly and easily find the common elements between two sets.




