LinkedHashMap
Java programming
data structures
get first entry
get last entry

Get first or last entry of a LinkedHashMap

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

LinkedHashMap is a widely used collection in Java that combines the uniqueness of keys, similar to a HashMap, with the ordering of entries, similar to a List. This data structure maintains a doubly-linked list through its entries, allowing it to remember the insertion order. This characteristic makes it particularly useful when you need a deterministic iteration order.

In this article, we'll explore techniques to get the first or last entry from a LinkedHashMap, understand its underlying mechanisms, and delve into the nuances that differentiate it from other maps.

Key Characteristics of LinkedHashMap

  • Maintains Order: Unlike HashMap, LinkedHashMap preserves the order of inserted elements.
  • Fast Iteration: Due to its doubly-linked list structure, iterating over a LinkedHashMap is generally more predictable.
  • Performance: Offers O(1) performance for basic operations like add, remove, and contains as it extends HashMap.

Retrieve the First Entry

Using an Iterator

To obtain the first entry of a LinkedHashMap, an iterator can be used on the entry set. Here's how you can accomplish that:

java
1LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
2map.put("A", 1);
3map.put("B", 2);
4map.put("C", 3);
5
6// Retrieve the first entry
7Map.Entry<String, Integer> firstEntry = map.entrySet().iterator().next();
8System.out.println("First Entry: " + firstEntry.getKey() + " = " + firstEntry.getValue());

Explanation

The method entrySet().iterator().next() acquires an iterator from the keys' ordered set and fetches the first element without removing it. It's efficient as it leverages the inherent order of LinkedHashMap.

Retrieve the Last Entry

Using an Iterator

Similar to retrieving the first entry, the last entry requires iterating through the map. However, given the iterator's nature, it requires us to traverse the entire map:

java
1Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
2Map.Entry<String, Integer> lastEntry = null;
3while(iterator.hasNext()) {
4    lastEntry = iterator.next();
5}
6System.out.println("Last Entry: " + lastEntry.getKey() + " = " + lastEntry.getValue());

Explanation

Though it requires traversing the map to reach the last entry, this solution still maintains efficiency due to LinkedHashMap's ordered nature.

Summary Table

Here's a quick reference comparing LinkedHashMap operations:

OperationMethodTime ComplexityExplanation
Get First EntryentrySet().iterator().next()O(1)Directly retrieves the first element
Get Last EntryIterate to the lastO(n)Traverses to fetch the last element
Insertionput()O(1)Similar to HashMap insertion
Search by KeycontainsKey()O(1)Efficient look-up by key

Technical Considerations

  • Synchronized Access: LinkedHashMap is not synchronized. If concurrent access is needed, consider wrapping it with Collections.synchronizedMap(new LinkedHashMap<>());.
  • Memory: Memory consumption can be slightly higher than HashMap due to the additional linked list pointers.
  • Removal Order: Besides maintaining insertion order, LinkedHashMap can be configured to maintain access order, which affects how elements are iterated after accessing.

Conclusion

The LinkedHashMap is a versatile map offering predictable iteration, akin to a list, while benefiting from the hashed map operations. While getting the first entry is straightforward, obtaining the last entry involves iterating through the collection. Understanding these methods can optimize data structure utilization, especially in scenarios demanding ordered entry access.

With this understanding, developers can harness LinkedHashMap's features effectively to manage collections that require consistent ordering, leading to more reliable and maintainable codebases.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.