Write a Java program to Copy Set content to another HashSet


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet. Next, the program defines a public class called Copy_HashSet.

Within the Copy_HashSet class, the main method is declared and serves as the entry point for the program. It takes an array of strings (a) as input. Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet h_set = new HashSet();. The specifies the type of elements that will be stored in the HashSet, which in this case is a string.

After that, several elements are added to the HashSet h_set using the add() method. The elements added are "Blue", "Green", "Black", "Orange", and "White". Next, the program prints the contents of the h_set HashSet using the System.out.println() statement.

The program then creates another HashSet called sub_set and adds elements to it using the add() method. The elements added are "Pink", "Yellow", and "Purple". The program then copies the elements from the sub_set HashSet to the h_set HashSet using the addAll() method. This method adds all the elements from the specified collection (in this case, sub_set) to the HashSet.

Finally, the program prints the contents of the updated h_set HashSet using the System.out.println() statement. This will display the elements in the h_set HashSet, which now includes the elements from the sub_set HashSet.

Source Code

import java.util.*;
public class Copy_HashSet
{
	public static void main(String a[])
	{
		HashSet<String> h_set = new HashSet<String>();
		h_set.add("Blue");
		h_set.add("Green");
		h_set.add("Black");
		h_set.add("Orange");
		h_set.add("White");
		System.out.println(h_set);
 
		HashSet<String> sub_set = new HashSet<String>();
		sub_set.add("Pink");
		sub_set.add("Yellow");
		sub_set.add("Purple");
		h_set.addAll(sub_set);
		System.out.println("Copy Set content to another HashSet ..");
		System.out.println(h_set);
	}
}

Output

[White, Blue, Black, Orange, Green]
Copy Set content to another HashSet ..
[White, Pink, Blue, Yellow, Purple, Black, Orange, Green]

Example Programs