In Java Collections Framework, the Set interface is extended from the Iterable interface which offering iterator, so we can use the enhanced for-loop statement and its iterator to iterate over elements

Apart from that, Java 8+ Set interface also provides the forEach(Consumer), internally is an enhanced for-each loop, for traversing a Set / HashSet

Let's walk through the below examples to explore them in more details

How to iterate a HashSet / Set?

Using the enhanced for-each loop

public void iterateWithForEach() {  
    Set<Integer> set = Set.of(3, 1, 2);

    for (int ele : set) {
        System.out.println(ele);
    }
}

Output

3  
1  
2  


Using the iterator

public void iterateWithIterator() {  
    Set<Integer> set = Set.of(3, 1, 2);
    Iterator<Integer> iterator = set.iterator();

    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

Output

3  
1  
2  


Using Java 8+ forEach(Consumer)

NullPointerException will be thrown if the specified consumer action or the caller list is null

public void iterateWithForEachConsumer() {  
    Set<Integer> set = Set.of(3, 1, 2);

    set.forEach(ele -> System.out.println(ele));
}

Output

3  
1  
2  


Troubleshooting

  • We can not use index loops (for-index, while-index or do-while-index loops) to iterate a HashSet / Set as there's no support of get element by index operation
  • Set.of is available since Java 9+
  • Set.forEach(Consumer) is available since Java 8+

Conclusion

In this tutorial, we learned some ways to iterate over a HashSet / Set by using the for-each loop, iterator and Java 8+ forEach(Consumer). You can find the full source code as below