Write a Java program to Create a HashSet with string items


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 Create_Hashset. Within the Create_Hashset 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, a new instance of the HashSet class is created using the constructor: HashSet<String> fr = new HashSet<String>();. 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 fr using the add() method. The elements added are "Mulberry", "Banana", "Mango", "Watermelon", "Apple", "Guava", and "Pineapple".
  • Finally, the program prints the contents of the fr HashSet using the System.out.println() statement.

Source Code

import java.util.*;
public class Create_Hashset
{
	public static void main(String[] args)
	{
		HashSet<String> fr = new HashSet<String>();
		fr.add("Mulberry");
		fr.add("Banana");
		fr.add("Mango");
		fr.add("Watermelon");
		fr.add("Apple");
		fr.add("Guava");
		fr.add("Pineapple ");
 
		System.out.println("Create a HashSet with string items : ");
		System.out.println(fr);
	}
}

Output

Create a HashSet with string items :
[Mulberry, Guava, Apple, Watermelon, Pineapple , Mango, Banana]

Example Programs