How to preserve insertion order in HashMap?
Switch from HashMap
to LinkedHashMap
to maintain insertion order. Differing from HashMap
, which doesn't commit to any specific order of entries, LinkedHashMap
logs the order in which keys are initially added.
Here is a quick example:
Iterating over it reflects the insertion sequence, making sure the output order mirrors the insertion order.
Detailed breakdown of LinkedHashMap
LinkedHashMap
is a subclass of HashMap
, with a doubly-inked list that preserves the entry order embedded within it. This class offers two specific modes:
- Insertion order (default mode): Preserves the original entry sequence.
- Access order: Entry order rearranges when an entry is accessed, which is triggered through the constructor.
Navigating special use cases
If you need a cache functionality that operates under the least-recently-used policy, LinkedHashMap
is the key, thanks to its unique access order mode.
Although TreeMap
preserves a sorted ordering of keys, it doesn't retain the insertion order. Alternatively, an ArrayList
of Pair
objects or Map.Entry
objects can be a good substitute when insertion order isn't a deal-breaker.
Unpacking performance notes
LinkedHashMap
upholds O(1) performance for addition, removal, and access operations in general, not deviating from HashMap
, but it ensures a predictable iteration order.
Further understanding with advanced hints
Here's some extra ammo for your LinkedHashMap
arsenal:
- Custom eviction policy: Override
removeEldestEntry()
for a size-limited cache that lets go of the eldest (classic eldest child syndrome, right?). - Serialization: Keep in mind, if serialization is on the cards, remember to factor in the additional overhead the linked list brings.
- Null keys & values: Yes,
LinkedHashMap
, likeHashMap
, allows null keys and values. Yet, bear in mind to tread carefully with these in multi-threaded contexts.
Was this article helpful?