Java program to find the union of HashSet collections

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

Problem Solution:

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

Program/Source Code:

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

// 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]

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

The addAll() method adds elements to a HashSet that are not contained in the specified HashSet.

Java HashSet Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.