Java Notes
Learn Java LinkedHashMap — a HashMap that maintains insertion order, how to iterate entries in insertion order, and a simple LRU cache implementation using access order mode.
LinkedHashMap is a HashMap that also maintains a doubly-linked list connecting all entries in insertion order. Every get, put, and iteration runs in O(1) — same as HashMap — but the iteration order is predictable.
Use LinkedHashMap when you need fast key-value lookup AND you want entries to come out in the order you put them in.
Basic Usage — Insertion Order Maintained
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
- Entries print in insertion order — Biryani, Dosa, Paneer Tikka, Lassi.
- Updating an existing key does not change its position in the order.
- HashMap would print in unpredictable order; LinkedHashMap never does.
Comparing HashMap vs LinkedHashMap vs TreeMap
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Simple LRU Cache Pattern
LinkedHashMap supports an access order mode — recently accessed entries move to the end. Combined with overriding removeEldestEntry(), you get a simple LRU (Least Recently Used) cache.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
user:2 was the least recently used, so it gets evicted when the 4th entry is added. This is the LRU pattern — exactly what database and web caches use.
Common Mistake: Expecting Same Order as TreeMap
Map<String, Integer> map = new LinkedHashMap<>();
map.put("c", 3);
map.put("a", 1);
map.put("b", 2);
System.out.println(map.keySet()); // {c, a, b} — insertion order, NOT sorted
// For sorted: use TreeMapLinkedHashMap preserves the order you inserted. It does not sort.
Practice Task
Task: Simulate a simple browser history using LinkedHashMap<String, String> (URL → page title). Visit 5 pages. Then print the history in visit order. Remove one page from the middle. Print the remaining history.
Hint: remove("url") removes by key. Iterate with entrySet() to print both URL and title.
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: History prints in visit order every time — guaranteed by LinkedHashMap. Change to HashMap — the order becomes random. Change to TreeMap — the order becomes alphabetical by URL, not visit order.
Continue the lesson path