LinkedHashMap

LinkedHashMap is a class in Java that extends the HashMap and maintains the insertion order of elements. It combines the features of a hash table (for fast lookups) with a linked list (for predictable iteration order). While HashMap stores the elements in a random order, LinkedHashMap retains the order in which entries were added.

Features

  • Maintains Insertion Order: Unlike HashMap, which does not guarantee any order, LinkedHashMap preserves the order in which key-value pairs are inserted. This makes it useful when you need to maintain the sequence of insertions.
  • Efficient Lookup and Iteration: Like HashMap, LinkedHashMap provides constant time complexity for the basic operations—get() and put()—on average. However, iteration over the keys or values is slower compared to a HashMap due to the extra overhead of maintaining a doubly-linked list.
  • Access Order (Optional): You can configure the LinkedHashMap to maintain order based on access order instead of insertion order. This means it will reorder the elements based on the most recently accessed elements, useful for implementing things like LRU (Least Recently Used) cache.

Constructor

We can create a LinkedHashMap using the following constructors:

  • LinkedHashMap(): Creates a default LinkedHashMap with an initial capacity and load factor.
  • LinkedHashMap(int initialCapacity): Creates a LinkedHashMap with a specified initial capacity.
  • LinkedHashMap(int initialCapacity, float loadFactor): Creates a LinkedHashMap with a specified initial capacity and load factor.
  • LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder): Creates a LinkedHashMap with an optional access order. If accessOrder is true, the order of iteration will be based on access, not insertion.

Example

Use Cases

  • Cache Implementation: Especially useful for LRU (Least Recently Used) caches.
  • Ordered Data Display: When you want to display data in the order it was added.
  • Preserving Order: For scenarios where order of data matters in maps.