Get Elements by Index from HashSet in Java Example

This example shows how to get elements by index from HashSet in Java. The example also shows how to get HashSet elements using an index using an iterator, for loop, array, and list.

How to get elements by index from HashSet in Java?

The HashSet is a collection of unique elements. The order of the elements returned by the HashSet iterator is not constant over time. The HashSet Java document has the below-given explanation for this behavior.

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It 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.

Plus, since the HashSet is backed by a HashMap, there are no methods to access its elements by index.

However, given all that, if you still want to access the elements by index, you can do so by below given ways.

1. Using an array

We can convert the HashSet object to an array and then access the elements using the index as given below.

Output

2. Using an ArrayList or LinkedList

Instead of an array, we can also convert the HashSet object to an ArrayList or a LinkedList and can then use the index.

Output

3. Using an Iterator or a for loop

We can also iterate the HashSet using an Iterator or an enhanced for loop to get the element located at the desired location as given below.

Output

We can also use enhanced for loop as given below.

Output

Important Note:

As we can see from the output above, even though we could get the elements by index, it is not in the order of the insertion. For example, we added element “10” first in the set, but in the output, we can see that it is at index 4. Plus, it is not even guaranteed that we will get the element “10” constantly at index 4.

The HashSet is not an appropriate choice of collection if you want to access the elements using an index. If your requirement is such, you should use any List implementation like LinkedList or ArrayList. If you want the Set functionality but want to maintain the insertion order of the elements, you can use the LinkedHashSet but then you will not be able to get elements by index.

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 *

Online Shopping