Iterate HashSet in Java

In this tutorial, we will learn how to Iterate HashSet in Java.

HashSet in Java extends AbstractSet and implements Set interface which is backed by hash table.  It creates a collection that uses a hash table for storage. This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits null element.

There are many ways to iterate HashSet in Java. We can iterate HashSet using Iterator or for loop or while loop etc. If we want to iterate using Iterator, then we need to get Iterator by calling the method iterator() on HashSet. Let’s see this with an example.

Example:

Output:

In the above program, we have iterated HashSet using an Iterator and for loop.

Related posts

Leave a Comment