Write a Java program to Find the union 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 Find_Union. Within the Find_Union 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 uni is created using the constructor: HashSet<Integer> uni = new HashSet<Integer>(nums1);. This creates a new HashSet uni and initializes it with the elements from nums1.
  • The addAll() method is then used to add all elements from nums2 to uni, which effectively performs the union operation. The union of two sets contains all unique elements from both sets.
  • Finally, the program prints the resulting union set uni using the System.out.print() statement.

Source Code

import java.util.*;
public class Find_Union
{
	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> uni = new HashSet <Integer> (nums1);
		uni.addAll(nums2);
 
		System.out.print("Union of HashSet1 and HashSet2 : " + uni);
	}
}

Output

HashSet 1 : [50, 20, 40, 10, 60, 30]
HashSet 2 : [80, 20, 70, 40, 10, 30]
Union of HashSet1 and HashSet2 : [80, 50, 20, 70, 40, 10, 60, 30]

Example Programs