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. IfaccessOrder
is true, the order of iteration will be based on access, not insertion.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import java.util.*; public class LinkedHashMapOperationsExample { public static void main(String[] args) { // Creating a LinkedHashMap with initial capacity 4 and default load factor LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); // 1. Add elements (put operation) map.put("One", 1); map.put("Two", 2); map.put("Three", 3); map.put("Four", 4); // Display the LinkedHashMap (insertion order is maintained) System.out.println("After put operations: " + map); // 2. Retrieve an element by key (get operation) System.out.println("Value for key 'Two': " + map.get("Two")); // 3. Check if a key exists (containsKey operation) System.out.println("Contains key 'Three'? " + map.containsKey("Three")); // 4. Check if a value exists (containsValue operation) System.out.println("Contains value 4? " + map.containsValue(4)); // 5. Remove an element by key (remove operation) map.remove("One"); System.out.println("After removing key 'One': " + map); // 6. Replace an existing value (replace operation) map.replace("Two", 22); // Replaces value for "Two" with 22 System.out.println("After replacing value for key 'Two': " + map); // 7. Clear all elements (clear operation) map.clear(); System.out.println("After clear operation: " + map); // 8. Check if the map is empty (isEmpty operation) System.out.println("Is the map empty? " + map.isEmpty()); } } //Output After put operations: {One=1, Two=2, Three=3, Four=4} Value for key 'Two': 2 Contains key 'Three'? true Contains value 4? true After removing key 'One': {Two=2, Three=3, Four=4} After replacing value for key 'Two': {Two=22, Three=3, Four=4} After clear operation: {} Is the map empty? true |
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.