Write a Java program to Print a HashSet collection using the foreach loop


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 Foreach_Loop. Within the Foreach_Loop 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 dif_type = new HashSet();. Since no specific type is specified within the diamond brackets (<>), it creates a raw HashSet that can store objects of any type.
  • After that, different types of elements are added to the dif_type HashSet using the add() method. The elements added include an integer (8), a string ("Tutor Joes"), a double (95.58), a character ('T'), a boolean (false), and another double (45.789784).
  • Finally, the program uses a foreach loop to iterate over the elements of the dif_type HashSet. The loop iterates over each element in the HashSet and assigns it to the variable it. Inside the loop, each element is printed using the System.out.println() statement.

Source Code

import java.util.*;
public class Foreach_Loop
{
	public static void main(String[] args) 
	{
		HashSet dif_type = new HashSet();
		dif_type.add(8);
		dif_type.add("Tutor Joes");
		dif_type.add(95.58);
		dif_type.add('T');
		dif_type.add(false);
		dif_type.add(45.789784);
 
		System.out.println("Print a HashSet collection using the foreach loop ..");
		for (Object it : dif_type)
		{			
			System.out.println( it);
		}
	}
}

Output

Print a HashSet collection using the foreach loop ..
T
false
Tutor Joes
8
45.789784
95.58

Example Programs