Java Program to Add a HashSet to Another HashSet Collection

Java program to add a HashSet to another HashSet collection

// Java program to add a HashSet to another 
// HashSet collection

import java.util.*;

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

    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);

    nums1.add(10);
    nums1.add(20);
    nums1.add(30);
    nums1.add(40);

    System.out.println("Set1: " + nums);
    System.out.println("Set2: " + nums1);

    nums.addAll(nums1);

    System.out.println("\nSet1: " + nums);
    System.out.println("Set2: " + nums1);
  }
}

Output

Set1: [1, 2, 3, 4]
Set2: [20, 40, 10, 30]

Set1: [1, 2, 3, 4, 20, 40, 10, 30]
Set2: [20, 40, 10, 30]
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment