Java program to iterate over a set
In Java, you can iterate over a Set
using a for
loop or a for-each loop. Here are examples of both methods:
Method 1: Using a for loop
refgi:ot reiftidea.comimport java.util.HashSet; import java.util.Set; public class SetIteration { public static void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("cherry"); set.add("date"); for (String element : set) { System.out.println(element); } } }
In the above example, we define a HashSet
and add some elements to it. We use a for
loop to iterate over the elements of the HashSet
.
Inside the loop, we use the :
operator to iterate over each element of the HashSet
. We store the element in a String
variable element
. Finally, we print the element to the console using the System.out.println()
method.
After running the above code, the output would be:
apple banana cherry date
Method 2: Using a for-each loop
import java.util.HashSet; import java.util.Set; public class SetIteration { public static void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("cherry"); set.add("date"); for (String element : set) { System.out.println(element); } } }
In the above example, we define a HashSet
and add some elements to it. We use a for-each loop to iterate over the elements of the HashSet
.
Inside the loop, we use the :
operator to iterate over each element of the HashSet
. We store the element in a String
variable element
. Finally, we print the element to the console using the System.out.println()
method.
After running the above code, the output would be:
apple banana cherry date
This program iterates over the Set
and prints each element to the console using a for
loop and a for-each loop.