How to Iterate over a Set/HashSet without an Iterator?
How can I iterate over a Set
/HashSet
without the following?
Iterator iter = set.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
Solution 1:
You can use an enhanced for loop:
Set<String> set = new HashSet<String>();
//populate set
for (String s : set) {
System.out.println(s);
}
Or with Java 8:
set.forEach(System.out::println);
Solution 2:
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");
Solution 3:
Converting your set into an array may also help you for iterating over the elements:
Object[] array = set.toArray();
for(int i=0; i<array.length; i++)
Object o = array[i];