Java LinkedHashMap
In this blog, we will explore one of the commonly used implementations of the Map interface in Java: LinkedHashMap. We will understand its internal working, all its important methods with examples and outputs, performance aspects, and when to use it.
What is LinkedHashMap?#
LinkedHashMap
is a class in Java that implements the Map
interface and extends HashMap
. Unlike HashMap
, it maintains the insertion order of elements.
Class Declaration#
Key Characteristics#
- Maintains insertion order using a doubly linked list.
- Allows one null key and multiple null values.
- Not synchronized (not thread-safe by default).
- Provides faster iteration compared to HashMap due to predictable order.
- Offers constant-time performance for basic operations like
get()
andput()
.
Internal Working of LinkedHashMap#
Internally, LinkedHashMap
works just like HashMap
but with an extra linked list that keeps track of the insertion order of entries.
Each node in LinkedHashMap contains:
- Key
- Value
- Hash
- Next node (for handling collisions)
- Before and after pointers (for doubly linked list)
When you insert an entry:
- The key's hash is used to find the bucket (like HashMap).
- The entry is also linked to the previous and next entry to maintain order.
Constructors#
- The last constructor maintains access order if
accessOrder
istrue
.
Important Methods with Examples#
1. put(K key, V value)
#
Inserts a key-value pair.
Output:
2. get(Object key)
#
Returns the value for the given key.
Output:
3. remove(Object key)
#
Removes the key-value pair.
Output:
4. containsKey(Object key)
#
Checks if the key exists.
Output:
5. containsValue(Object value)
#
Checks if the value exists.
Output:
6. keySet()
#
Returns a set of keys.
Output:
7. values()
#
Returns a collection of values.
Output:
8. entrySet()
#
Returns a set of key-value pairs.
Output:
9. clear()
#
Removes all entries from the map.
Output:
Performance of LinkedHashMap#
- Basic operations like
get()
,put()
,remove()
are O(1) on average. - Slightly slower than
HashMap
due to the overhead of maintaining the insertion order. - Provides predictable iteration, which is useful when order matters.
When to Use LinkedHashMap#
- When you need fast lookups and also want to maintain insertion order.
- When you want predictable iteration order.
- When you’re implementing an LRU (Least Recently Used) cache using access order.
Conclusion#
In this blog, we explored the LinkedHashMap
class in Java:
- It maintains insertion order unlike
HashMap
. - Internally uses a doubly linked list along with hash buckets.
- We learned about all important methods like
put()
,get()
,remove()
,keySet()
, andentrySet()
. - We understood its performance characteristics, how it works, and when it should be used.
LinkedHashMap is a powerful and versatile implementation of the Map interface, especially useful when order matters. In the next blog, we’ll dive into TreeMap
and explore how it maintains a sorted order of keys.