1. Iterate the HashSet using iterator.
2. Iterate the HashSet using for each loop.
1. Program for How to Iterate HashSet Using Iterator
import java.util.*; public class HashSetIteratorExample { public static void main(String args[]) { // Declaring a HashSet HashSet<String> hashset = new HashSet<String>(); // Add elements to HashSet hashset.add("Pear"); hashset.add("Apple"); hashset.add("Orange"); hashset.add("Papaya"); hashset.add("Banana"); // Get iterator Iterator<String> it = hashset.iterator(); // Show HashSet elements System.out.println("HashSet contains: "); while(it.hasNext()) { System.out.println(it.next()); } } }
Output
HashSet contains:
Apple Pear Papaya Orange Banana
2. Program for How to Iterate HashSet using for each loop
import java.util.*; public class HashSetIteratorExample { public static void main(String args[]) { // Declaring a HashSet HashSet<String> hashset = new HashSet<String>(); // Add elements to HashSet hashset.add("Pear"); hashset.add("Apple"); hashset.add("Orange"); hashset.add("Papaya"); hashset.add("Banana"); System.out.println("HashSet contains :"); // Using for each loop for(String str : hashset){ System.out.println(str); } } }
Output
HashSet contains :
Apple Pear Papaya Orange Banana