Java program to find the union of HashSet collections
// Java program to find the union 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();
nums1.add(1);
nums1.add(2);
nums1.add(3);
nums1.add(4);
nums1.add(5);
nums1.add(6);
nums2.add(1);
nums2.add(2);
nums2.add(3);
nums2.add(4);
nums2.add(7);
nums2.add(8);
System.out.println("Elements of nums1 set are: " + nums1);
System.out.println("Elements of nums2 set are: " + nums2);
HashSet < Integer > union = new HashSet < Integer > (nums1);
union.addAll(nums2);
System.out.print("Union of nums1 and nums2: " + union);
}
}
Output
Elements of nums1 set are: [1, 2, 3, 4, 5, 6]
Elements of nums2 set are: [1, 2, 3, 4, 7, 8]
Union of nums1 and nums2: [1, 2, 3, 4, 5, 6, 7, 8]