Skip to content

Find Key Index in LinkedHashMap in Java Example

This example shows how to find a key index in LinkedHashMap in Java. The example also shows how to find the index of the key in LinkedHashMap using ArrayList and Iterator.

How to find the key index in LinkedHashMap in Java?

The LinkedHahMap class being a map implementation does not allow us to access keys or values using the index. However, if you still want, there are several ways using which you can do that as given below.

1. Using an ArrayList

You can get all the keys from the LinkedHashMap using the keySet method, convert key set to an ArrayList and then use the indexOf method of the ArrayList class to find the index.

Output

2. Using LinkedList

Instead of converting the key set to ArrayList, you can also convert it to the LinkedList and then use the indexOf method of the LinkedList class to find the key index.

Output

3. Using an Iterator

You can iterate through all keys of the LinkedHashMap using an Iterator and find the index as given below.

Output

Important Notes:

1. If the LinkedHashMap keys are objects of the custom class, then the custom class must implement the equals method (and ideally hashCode method as well) for any of the three approaches to work.

2. None of the above approaches perform well if the map is too large as all of them require iterating the map to find the key index. Plus, creating an ArrayList or LinkedList just to find the index is an additional overhead.

3. If you really need to access the keys or values using the index, then consider using the list based collection instead of the LinkedHashMap.

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

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

References:
Java 8 LinkedHashMap

About the author

Leave a Reply

Your email address will not be published.