There are at least six additional ways to iterate over a set. The following are known to me:
Method 1
// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
Method 2
for (String movie : movies) {
System.out.println(movie);
}
Method 3
String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
System.out.println(movieArray[i]);
}
Method 4
// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
System.out.println(movie);
});
Method 5
// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));
Method 6
// Supported in Java 8 and above
movies.stream().forEach(System.out::println);
This is the HashSet
which I used for my examples:
Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");