How to Iterate over a Set/HashSet without an Iterator? How to Iterate over a Set/HashSet without an Iterator? java java

How to Iterate over a Set/HashSet without an Iterator?


You can use an enhanced for loop:

Set<String> set = new HashSet<String>();//populate setfor (String s : set) {    System.out.println(s);}

Or with Java 8:

set.forEach(System.out::println);


There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete CollectionEnumeration 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 abovemovies.stream().forEach((movie) -> {  System.out.println(movie);});

Method 5

// Supported in Java 8 and abovemovies.stream().forEach(movie -> System.out.println(movie));

Method 6

// Supported in Java 8 and abovemovies.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");


Converting your set into an arraymay also help you for iterating over the elements:

Object[] array = set.toArray();for(int i=0; i<array.length; i++)   Object o = array[i];