Get Value from LinkedHashMap by Index in Java Example

This example shows how to get a value from the LinkedHashMap object using the index. The example also shows various ways to get the value using index from LinkedHashMap instead of the key.

How to get a value from LinkedHashMap by index in Java?

Even though the LinkedHashMap class is a linked list implementation of the Map interface, it looks more like a map than the linked list. The class has not exposed any methods using which you can access entries (key-value mappings) using the index. The reason is, like with any other regular map implementations, we are supposed to access the LinkedHashMap values using keys, not using index.

However, you can still do that if you want in below given ways.

1. Using keys array

You can get all keys of the LinkedHashMap using the keySet method, convert the set to an array using the toArray method, access the key using array index and then get the value for that key from the LinkedHashMap as given below.

Output

2. Using the List

Instead of converting to an array, you can also convert the key set to an ArrayList or LinkedList and then access the key using index.

Output

3. Using an Iterator

You can get all the entries from the LinkedHashMap using the entrySet method, iterate through them using the hasNext and next method of the iterator while maintaining the index counter and get the value for the desired index as given below.

Output

Important Note:

None of the above approaches should be used as they do not perform well especially if the map is large. All of them require iterating through the LinkedHashMap directly (approach 3) or indirectly (approaches 1 and 2). Plus, approaches 1 and 2 requires allocating a new array or ArrayList to perform this task which is a costly operation.

If you really need to access the values using index instead of the keys, then I think you should use other index-based collections (like List) instead of the LinkedHashMap.

This example is a part of the LinkedHashMap in Java Tutorial.

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

References:
Java 8 LinkedHashMap

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 *