Java > Java Collections Framework > List, Set, and Map Interfaces > LinkedHashMap
LinkedHashMap Example: Maintaining Insertion Order
LinkedHashMap
is a subclass of HashMap
that maintains the order in which keys were inserted. This example demonstrates how LinkedHashMap
preserves insertion order and how it can be useful.
Basic LinkedHashMap Usage
This code snippet demonstrates the basic operations of a LinkedHashMap
, including insertion, iteration, retrieval, checking for key existence, and removal. The output will show that the elements are iterated in the same order they were inserted. The example utilizes the java.util.LinkedHashMap
and java.util.Map
classes.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
// Creating a LinkedHashMap
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
// Adding key-value pairs
linkedHashMap.put("Apple", "Red");
linkedHashMap.put("Banana", "Yellow");
linkedHashMap.put("Orange", "Orange");
linkedHashMap.put("Grape", "Purple");
// Iterating over the LinkedHashMap. The order is preserved.
System.out.println("LinkedHashMap contents:");
for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
// Accessing elements by key
String color = linkedHashMap.get("Banana");
System.out.println("\nColor of Banana: " + color);
// Checking if a key exists
boolean containsKey = linkedHashMap.containsKey("Orange");
System.out.println("\nContains key 'Orange': " + containsKey);
// Removing an element
linkedHashMap.remove("Apple");
System.out.println("\nLinkedHashMap after removing 'Apple':");
for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Concepts Behind the Snippet
LinkedHashMap
extends HashMap
and adds the capability to maintain insertion order or access order. This is achieved using a doubly-linked list running through all of its entries. It provides predictable iteration order, which is not guaranteed by HashMap
. When 'accessOrder' is set to true in the constructor, the LinkedHashMap
will maintain access order. Every get or put operation will move the accessed element to the end of the list.
Real-Life Use Case
A practical application of LinkedHashMap
is implementing a Least Recently Used (LRU) cache. By setting 'accessOrder' to true and overriding the removeEldestEntry()
method, you can automatically evict the least recently used entries when the cache reaches its maximum capacity. This is very useful in web servers or database caching scenarios.
Best Practices
LinkedHashMap
, as it requires more memory than HashMap
due to the doubly-linked list.HashMap
and LinkedHashMap
, consider whether maintaining order is a strict requirement. If order is not important, HashMap
offers slightly better performance.removeEldestEntry()
method is correctly implemented to maintain the desired cache size.
Interview Tip
Be prepared to discuss the differences between HashMap
and LinkedHashMap
, including their performance characteristics and use cases. Explain how LinkedHashMap
maintains order and how it can be used to implement an LRU cache. Also understand the difference between insertion order and access order.
When to Use Them
Use LinkedHashMap
when you need to maintain the order of elements in which they were inserted or accessed. This is particularly useful when the iteration order matters, such as in configuration files, caching mechanisms, or situations where you want to process elements in a specific sequence.
Memory Footprint
LinkedHashMap
has a larger memory footprint compared to HashMap
because it stores additional pointers to maintain the doubly-linked list. This can be a significant consideration when dealing with large datasets. Each entry stores pointers to the next and previous entry which increases the memory usage in comparison to HashMap.
Alternatives
HashMap
: If order doesn't matter and performance is critical.TreeMap
: If you need elements to be sorted by keys. Requires keys to implement the Comparable
interface or to provide a Comparator
.ConcurrentHashMap
: Thread-safe implementation for concurrent environments.
Pros
TreeMap
when sorting is not required.
Cons
HashMap
.HashMap
for basic operations (insertion, retrieval, deletion) due to the overhead of maintaining the linked list.
FAQ
-
What is the difference between
HashMap
andLinkedHashMap
?
HashMap
does not guarantee any particular order of elements, whileLinkedHashMap
maintains either the order in which elements were inserted or the order in which they were accessed (LRU).LinkedHashMap
is slightly slower and requires more memory thanHashMap
. -
How can I implement an LRU cache using
LinkedHashMap
?
Create aLinkedHashMap
withaccessOrder
set totrue
in the constructor. Override theremoveEldestEntry()
method to returntrue
when the cache size exceeds a certain limit. This will automatically remove the least recently used entry. -
When should I use
LinkedHashMap
overTreeMap
?
UseLinkedHashMap
when you need to maintain insertion order or access order, and you don't require the elements to be sorted by their keys.TreeMap
provides sorted order based on keys, which incurs a performance cost if sorting is not necessary.