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

user1621988 picture user1621988 · Sep 17, 2012 · Viewed 720.1k times · Source

How can I iterate over a Set/HashSet without the following?

Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

Answer

assylias picture assylias · Sep 17, 2012

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);