As we have seen the implementations of a Set are :
Let us see the HashSet implementation first,
Say, we have a HashSet with values, Tom, John and Java.
Now, let us see the how to iterate a HashSet.
import java.util.*;
public class MyApplication {
public static void main(String[] args) {
Set x = new HashSet<>();
x.add("Tom");
x.add("John");
x.add("Java");
for (String i : x) {
System.out.println(i);
}
}
}
Similarly, in the above code we have created a HashSet.
Setx = new HashSet<>();
And initialised to the variable x.
x.add("Tom");
x.add("John");
x.add("Java");Below is how they are placed in the HashSet.

In the next line we have used the for each loop to Iterate through the HashSet.
for (String i : x) {
System.out.println(i);
}Now, if we see the iterations of for loop,
for (String i : x) {
System.out.println(i);
}In the first Iteration the first value of the HashSet x (i.e. Java) is taken and put into the variable i.

And the print statement, prints the value of i.
Similarly, in the second Iteration the second value of the HashSet x (i.e. Tom) is taken and put into the variable i.

And the print statement, prints the value of i.
Similarly, in the third Iteration the third value of the HashSet x (i.e. John) is taken and put into the variable i.

And the print statement, prints the value of i.
Next, let us look at Iterating a LinkedHashSet.
import java.util.*;
public class MyApplication {
public static void main(String[] args) {
Set x = new LinkedHashSet<>();
x.add("Tom");
x.add("John");
x.add("Java");
for (String i : x) {
System.out.println(i);
}
}
}
Similarly, in the above code we have created a LinkedHashSet.
Setx = new LinkedHashSet<>();
And initialised to the variable x.
x.add("Tom");
x.add("John");
x.add("Java");Below is how they are placed in the HashSet.

In the next line we have used the for each loop to Iterate through the LinkedHashSet.
for (String i : x) {
System.out.println(i);
}And we get the below output,