Skip to content

Get First or Last Entry of LinkedHashMap in Java Example (Remove)

This example shows how to get the first or last entry of the LinkedHashMap in Java. The example also shows how to remove the first or last entry of the LinkedHashMap using various ways.

How to get the first or last entry of the LinkedHashMap in Java?

The LinkedHashMap class is an implementation of the hash table and linked list of the Map interface. It maintains the references to the head and tail of the list, but it is internal and not exposed via any methods.  However, there are several ways using which you can get the first or last entry of the LinkedHashMap in Java.

1. Using Iterator

Since there is no exposed method to access the first or last element of the LinkedHashMap, iterating the LinkedHashMap object will be the simplest solution.

Output

If you want to remove the first entry or last entry from the map, you can use below given code after the while loop.

Output

Note: This approach requires you to iterate the whole map object and may not perform if the map is too large.

2. By converting it to an array

You can get all keys of the LinkedHashMap object using the keySet method and then convert it to an array using the toArray method. Once you get an array of keys, you can access the first and last key of the LinkedHashMap using the array index as given below.

Output

Note: This approach requires the allocation of a new array which is costly operation especially if the map is large. Iterating through the map is better in that case.

3. By converting it an ArrayList or LinkedList

Instead of an array, you can also convert the key set to an ArrayList or LinkedList.

Output

The LinkedList class provides the getFirst and getLast methods to access the first and last element respectively. You can use that too.

Output

Note: Same as an array approach, this approach needs to allocate memory for new ArrayList or LinkedList object which is costly in terms of performance.

4. Using the reflection

This option is just for the educational purpose, you should not use this in production. The LinkedHashMap class maintains the first and last entry in member variables named head and tail respectively, but they are private to the class. To access these fields, we need to make them accessible using the reflection API.

Output

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

Leave a Reply

Your email address will not be published.