Skip to content

Get LinkedHashSet Elements By Index in Java Example

This example shows how to get LinkedHashSet elements by index in Java. This example also shows how to get elements by index from LinkedHashSet using an array, ArrayList, and iterator.

How to get elements by index from LinkedHashSet in Java?

The LinkedHashSet in Java is a hash table and linked list implementation of the Set interface. The LinkedHashSet class maintains a doubly-linked list running through elements but does not expose any methods using which we can get the elements using the index. However, if you still want you can access the elements by index as given below.

1. By converting to an array

We can convert LinkedHashSet to an array and then we can access the elements from the array using the index as given below.

Output

Note: This approach needs the allocation of a new array with the linked hash set elements. If the LinkedHashSet contains large number of elements, it may not perform well. Plus, you need to convert to array every time there is a change in the set object. Use this only if the set is not changed much and you need to access large number of elements using the index.

2. By converting to a List

Instead of an array, we can also convert the LinkedHashSet to a List like ArrayList or LinkedList object and then we can access the elements from the List using the index and get method.

Output

Note: Similar to the array approach, this needs a linked hash set object to be converted to the List which is a costly operation and may not perform well especially if the LinkedHashSet is very big. Only use this approach if you need to access large number of elements using the index and set is not changed much.

3. By iterating the Set

We can also iterate the LinkedHashSet elements while maintaining an index counter and when we reach the desired index, we can get that element as shown below.

Output

Instead of an iterator, we can also use the enhanced for loop as given below.

Output

Important Note:

If the requirement is to access a very large number of elements by their indices, LinkedHashSet may not be a proper collection to use. Check if you can use the List based implementations like ArrayList or a LinkedList instead of the LinkedHashSet.

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

Leave a Reply

Your email address will not be published.