3 different ways to iterate over a HashSet in Java

How to iterate over HashSet items in Java

HashSet is used to store unique collections of items in Java. To iterate over a HashSet, we have different ways. The recommended and easiest way to solve this is by using a for loop.  We can also create one iterator and iterate through the HashSet.

There are other ways as well that we can use to iterate over a HashSet.  In this post, we will learn how to iterate over the items of a HashSet in different ways.

By using an iterator:

Let’s try with an iterator first.

import java.util.HashSet;
import java.util.Iterator;

class Example{
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<>();

        hashSet.add("one");
        hashSet.add("two");
        hashSet.add("three");
        hashSet.add("four");
        hashSet.add("five");

        Iterator<String> it = hashSet.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}

Here,

  • hashSet is the hashset that can store strings.
  • We added five different strings to this HashSet
  • The iterator is created by using the iterator() method. it.hasNext() checks if we have any more items or not in the HashSet. If yes, we are printing the value.

It will give an output as like below: java iterate hashset

By using a for loop:

We can also use a for loop to iterate through the items of the HashSet. It is simpler and we don’t have to create an iterator separately.

import java.util.HashSet;

class Example{
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<>();

        hashSet.add("one");
        hashSet.add("two");
        hashSet.add("three");
        hashSet.add("four");
        hashSet.add("five");

        for (String s : hashSet) {
            System.out.println(s);
        }
    }
}

It will give similar output.

By using forEach:

forEach is another quick and easy way to iterate through a HashSet in Java.

class Example{
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<>();

        hashSet.add("one");
        hashSet.add("two");
        hashSet.add("three");
        hashSet.add("four");
        hashSet.add("five");

        hashSet.forEach(System.out::println);
    }
}

It will print the same output.

You can pick any one of these methods to iterate over a HashSet in Java.

You might also like: