Write a Java program to Find the intersection of HashSet collections
The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet.
- The program defines a public class called Intersection. Within the Intersection class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.
- Inside the main method, two instances of the HashSet class are created: nums1 and nums2. Both sets contain Integer objects.
- The program adds some elements to nums1 using the add() method, and then adds different elements to nums2. These sets represent two sets of numbers.
- After that, the program prints the contents of nums1 and nums2 using the System.out.println() statement.
- Next, a new HashSet called inter is created using the constructor: HashSet<Integer> inter = new HashSet<Integer>(nums1);. This creates a new HashSet inter and initializes it with the elements from nums1.
- The retainAll() method is then used to retain only the elements that are present in nums2 in the inter set. This effectively performs the intersection operation. The intersection of two sets contains only the common elements between the two sets.
- Finally, the program prints the resulting intersection set inter using the System.out.print() statement.
Source Code
import java.util.*;
public class Intersection
{
public static void main(String[] args)
{
HashSet <Integer> nums1 = new HashSet<Integer>();
nums1.add(10);
nums1.add(20);
nums1.add(30);
nums1.add(40);
nums1.add(50);
nums1.add(60);
HashSet <Integer> nums2 = new HashSet<Integer>();
nums2.add(10);
nums2.add(20);
nums2.add(30);
nums2.add(40);
nums2.add(70);
nums2.add(80);
System.out.println("HashSet 1 : " + nums1);
System.out.println("HashSet 2 : " + nums2);
HashSet <Integer> inter = new HashSet <Integer> (nums1);
inter.retainAll(nums2);
System.out.print("Intersection of HashSet1 and HashSet2 : " + inter);
}
}
Output
HashSet 1 : [50, 20, 40, 10, 60, 30]
HashSet 2 : [80, 20, 70, 40, 10, 30]
Intersection of HashSet1 and HashSet2 : [20, 40, 10, 30]