How can I iterate over a Set
/HashSet
without the following?
Iterator iter = set.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
How can I iterate over a Set
/HashSet
without the following?
Iterator iter = set.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
Converting your set into an array may also help you for iterating over the elements:
Enumeration(?):
Another way (java.util.Collections.enumeration()):
Java 8:
or
You can use functional operation for a more neat code
You can use an enhanced for loop:
Or with Java 8:
There are at least six additional ways to iterate over a set. The following are known to me:
Method 1
Method 2
Method 3
Method 4
Method 5
Method 6
This is the
HashSet
which I used for my examples:Here are few tips on how to iterate a Set along with their performances:
The code is self explanatory.
The result of the durations are:
We can see the
Lambda
takes the longest whileIterator
is the fastest.