Iterate HashSet in Java Example

This example shows how to iterate HashSet in Java. This example also shows how to iterate Java HashSet using for loop, HashSet iterator, and forEach.

How to iterate HashSet in Java?

The Set is not an index based collection hence the HashSet class does not provide any methods to get elements by their index. For example, the ArrayList get method accepts the index argument and returns an element located at the specified index.

Since there is no method to get the HashSet elements by index, we have to iterate over the HashSet to get elements from it.

There are several ways using which we can iterate over elements of the HashSet object in Java as given below.

1. Iterate using for loop

We can use the enhanced for loop to iterate through the elements of the HashSet object as given below.

Output

2. Iterate using an Iterator

The iterator method of the HashSet class returns an iterator object over the elements of this set object.

Once we get the iterator object using the HashSet iterator method, we can iterate through elements of the set using the hasNext and next methods as given below.

Output

3. Iterate using forEach

If you are using Java version 8 or later, you can also use the forEach to iterate over the elements as given below.

Output

Important Note:

You may have observed that the order of the HashSet elements is not the same as the insertion order. For example, the element “Two” was inserted first, but in the output, it was printed last.

The reason is, the List is an ordered collection while the Set is not. It means that the List interface guarantees to return the elements in the same order in which they were inserted. However, the Set interface does not make any such guarantee. When you retrieve elements from the Set, they may be returned in a different order depending upon the type of Set implementation class.

The HashSet class does not make any guarantee the order. In other words, the order of the elements may not remain constant over time. If you want to use the Set but still want to maintain the insertion order of the elements, use the LinkedHashSet instead of the HashSet class.

This example is a part of the HashSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 HashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *