LinkedHashMap
LinkedHashMap is a variation of HashMap that maintains the insertion order of key-value pairs, meaning entries appear in the exact order they were added.
1. What is LinkedHashMap?
LinkedHashMap is a variation of HashMap that maintains the insertion order of key-value pairs, meaning entries appear in the exact order they were added.
2. Why is it used?
It's useful when you need the fast lookup benefits of a HashMap, but also want the entries to appear in a predictable, consistent order — for example, when displaying recently added items in the order they were added.
3. Real-Life Example
Think of a reception logbook where visitor entries are recorded strictly in the order they arrive, even though each visitor also has a unique ID for lookup. LinkedHashMap preserves this same kind of arrival order.
4. Syntax
javaLinkedHashMap<KeyType, ValueType> mapName = new LinkedHashMap<>();
5. Example Program
javaimport java.util.LinkedHashMap; public class LinkedHashMapDemo { public static void main(String[] args) { LinkedHashMap<String, Integer> scores = new LinkedHashMap<>(); scores.put("Ankit", 70); scores.put("Meera", 95); System.out.println(scores); } }
Output:
{Ankit=70, Meera=95}6. Key Points to Remember
LinkedHashMappreserves insertion order, unlikeHashMap.- It's slightly slower than
HashMapdue to the extra bookkeeping needed to maintain order. - It can also be configured to maintain access order instead of insertion order, useful for building simple caches.