You can iterate a HashSet by using either forEach(Consumer), since Java 8, or for-each loop, Iterator, and SplitIterator

The iteration order is unpredictable as HashSet has no guarantee to it

Index-loops such as for-index, while-index, do-while-index cannot be used to iterate a HashSet as it has no support on retrieving element by index

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

Iterate with Java 8+ forEach(Consumer)

  • Use forEach(Consumer), since Java 8, to iterate over a HashSet

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

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

    set.forEach(ele -> System.out.printf("%d ", ele));
}

Iterate with a for-each loop

  • Use a for-each loop to iterate over a HashSet
@Test
public void iterateWithForEach() {  
    Set<Integer> set = new HashSet<>(Set.of(3, 1, 2));

    for (int ele : set) {
        System.out.printf("%d ", ele);
    }
}

Iterate with Iterator and SplitIterator

  • Use Iterator and SplitIterator to iterate over a collection in normal and parallel respectively

    You can remove an element when iterating with an iterator while other methods can't

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

    while (iterator.hasNext()) {
        System.out.printf("%d ", iterator.next());
    }
}

Conclusion

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


Share to social

Van N.

Van N. is a software engineer, creator of HelloKoding. He loves coding, blogging, and traveling. You may find him on GitHub and LinkedIn