×

Java program to find the difference between HashSet collections

Given two HashSet collections, we have to find the difference.
Submitted by Nidhi, on May 12, 2022

Problem statement

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

Source Code

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

```// Java program to find the difference between
// 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 > difference = new HashSet < Integer > (nums1);
difference.removeAll(nums2);

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

Output

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

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 difference of nums1, nums2 using removeAll() method.

The removeAll() method removes elements from a HashSet that are contained in a specified HashSet.

Student's Section
Subscribe