Iterating over HashSet in Java In our last Java collection tutorial we have seen How
to iterate over ArrayList in Java and in this tutorial we will see How to
iterate over HashSet in Java. There are two ways to iterate, loop or traverse
over HashSet in Java, first using advanced for-each loop added on Java 5
and second using Iterator
which is more conventional way of iterating over HashSet
in Java. Now questions is When should you use for loop and when Iterator is
appropriate option. Well I usually use for loop If I only read from HashSet and
doesn't remove any element, while Iterator is preferred approach. You should
not remove elements from HashSet
while iterating over it in for loop, Use Iterator to do that.