Java
Map Interface
Java Classes
Insertion Order
Data Structures

Java Class that implements Map and keeps insertion order?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In the world of Java development, handling collections efficiently is essential. When it comes to mapping key-value pairs while maintaining the insertion order, LinkedHashMap is the Java class designed to meet these requirements. It is a part of the Java Collections Framework and extends HashMap, adding predictable iteration order to it.

Understanding LinkedHashMap

LinkedHashMap is an implementation of the Map interface and inherits HashMap's characteristics, including its capacity for storing key-value pairs and allowing keys to be any non-null object. What distinguishes LinkedHashMap from HashMap is its capability to maintain the order of elements as they are inserted, which can be exceedingly valuable when you need to retrieve elements in the order they were added, or in the least-recently accessed order.

The core mechanics rely on a doubly-linked list running through its entries. This linked list defines the iteration ordering, which, by default, is the order in which keys were inserted into the map (insertion-order). Optionally, if the constructor is used with an access order boolean set to true, it maintains the keys in the order they were last accessed, from least-recently accessed to most-recently (access-order).

How LinkedHashMap Works

LinkedHashMap internally uses the same table structure as HashMap, with the addition of a linked list holding references to the table entries. Each entry in the map is an instance of the Entry class, which besides key, value, and hash, also contains pointers named before and after that handle the double-linking of entries.

The iteration over the map therefore can afford to be predictable in contrast to HashMap, since it's effectively iterating over a linked list. From a performance perspective, the time complexity for basic operations like add(), remove(), and contains() is constant time, O(1), under typical conditions. However, performance can degrade to O(n) if the map gets very large or the initial capacity is extremely low.

Practical Example of LinkedHashMap

Here's a basic example demonstrating the usage of a LinkedHashMap:

java
1import java.util.LinkedHashMap;
2import java.util.Map;
3
4public class DemoLinkedHashMap {
5    public static void main(String[] args) {
6        Map<Integer, String> orderedMap = new LinkedHashMap<>();
7
8        orderedMap.put(1, "one");
9        orderedMap.put(2, "two");
10        orderedMap.put(3, "three");
11
12        // Iterating over keys, which will be in the order: 1, 2, 3
13        for (Integer key : orderedMap.keySet()) {
14            System.out.println("Key: " + key + ", Value: " + orderedMap.get(key));
15        }
16    }
17}

When run, this example illustrates that the output retains the order of insertion:

 
Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three

This predictable order can be leveraged in applications where data retrieval needs to mirror data entry sequence or the relative timing of entries needs preservation.

Key Points Summary

FeatureDescriptionUse-Case
Insertion orderMaintains elements in the order they were addedRetrieving values in order of insertion
Access orderMaintains elements based on the order of last access manipulation (least to most recently accessed)Caching scenarios where the least recently accessed items might be removed
ComplexityInsert, remove, contains operations have a time complexity of O(1)Efficient for data manipulation

Conclusion

LinkedHashMap is therefore an incredibly useful Java collection class when both mapping capabilities and predictable iteration are required. Its versatility allows it to be applied in various scenarios, notably where the insertion and access order are crucial. Equally important, it satisfies use cases that involve a blend of hash table and linked list characteristics without compromising much on performance, making it an ideal choice for both simple and complex data handling needs.


Course illustration
Course illustration

All Rights Reserved.