Find Element Index in Java LinkedHashSet Example

This example shows how to find the element index in Java LinkedHashSet. This example also shows how to find the index of an element in LinkedHashSet using ArrayList, array, and iterator.

How to find the element index in LinkedHashSet in Java?

The LinkedHashSet class does not have any publicly accessible methods using which we can work with the element index. It internally manages a linked list for all of its elements, but there are no public methods to get LinkedHashSet elements by index. However, we can still find the index of the elements using approaches given below.

1. By converting to a List

We can convert LinkedHashSet object to a List like ArrayList or a LinkedList and then we can use the indexOf method to find the element index as given below.

Output

Note: If you want to search for many elements, convert linked hash set to List only once and then use the indexOf method to increase the performance. In general, this approach should not be used as it creates a new List from the LinkedHashSet elements and may slow down the performance if the LinkedHashSet has a very large number of elements.

2. Using the iterator or enhanced for loop

We can iterate through elements of LinkedHashSet object using an iterator and get the index of the desired element as given below.

Output

3. Using Apache Commons

We can also convert the LinkedHashSet object to an array and then we can use the indexOf method of the ArrayUtils class of the Apache commons library to find the index in the array.

Output

Note: Similar to the List approach, this approach needs to allocate a new array having linked hash set elements and may not perform well for large LinkedHashSet object.

Consider using an index based data structure like a List (ArrayList or LinkedList) instead of LinkedHashSet class.

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

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

References:
Java 8 LinkedHashSet

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 *