×

# Java program to find the intersection of HashSet collections

Given a HashSet, we have to find the intersection.
Submitted by Nidhi, on May 11, 2022

## Problem statement

In this program, we will create two sets using the HashSet collection to store integer elements. Then we will find the intersection of HashSet collections using the retainAll() method and assign the result to a new HashSet collection.

## Source Code

The source code to find the intersection of HashSet collections is given below. The given program is compiled and executed successfully.

```// Java program to find the intersection of
// HashSet collections

import java.util.*;

public class Main {
public static void main(String[] args) {
HashSet < Integer > nums1 = new HashSet();
HashSet < Integer > nums2 = new HashSet();

System.out.println("Elements of nums1 set are: " + nums1);
System.out.println("Elements of nums2 set are: " + nums2);

HashSet < Integer > intersection = new HashSet < Integer > (nums1);
intersection.retainAll(nums2);

System.out.print("Intersection of nums1 and nums2: " + intersection);
}
}
```

### Output

```Elements of nums1 set are: [1, 2, 3, 4, 5, 6]
Elements of nums2 set are: [1, 2, 3, 4, 7, 8]
Intersection of nums1 and nums2: [1, 2, 3, 4]
```

## Explanation

In the above program, we imported the "java.util.*" package to use the HashSet collection. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. Here, we created two sets to store integer data elements using HashSet collection. Then we calculated the intersection of nums1, nums2 using retainAll() method.

The retainAll() method removes elements from a HashSet that are not contained in the specified HashSet.