LinkedHashMap Example in Java
Problem
A LinkedHashMap keeps its entries in the exact order they were inserted, unlike a plain HashMap, whose iteration order isn't guaranteed at all.
Add several entries to a LinkedHashMap in a specific order and show that iterating it always visits them in that same order.
Java Program
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("Banana", 2);
scores.put("Apple", 5);
scores.put("Cherry", 3);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}Output
Core Logic
LinkedHashMap keeps an internal linked list threading through its entries in the order they were added, alongside the usual hash table structure, so iteration always follows that same order.
- 1
new LinkedHashMap<String, Integer>()creates a map that behaves like a HashMap for lookups, but also remembers insertion order. - 2
put("Banana", 2),put("Apple", 5), andput("Cherry", 3)insert entries in that exact order. - 3Iterating with
entrySet()visitsBanana, thenApple, thenCherry— the same order they were inserted in, not alphabetical or any other order. - 4A plain
HashMapholding the exact same three entries would make no such promise — its iteration order could come out differently, and isn't required to match insertion order at all.
Apple would sort before Banana alphabetically, the map still prints Banana first, since it was inserted first.Key Point: LinkedHashMap sits between HashMap and TreeMap — it doesn't sort entries the way TreeMap does, but unlike HashMap, its iteration order is fully predictable: always insertion order.
Why: put() and get() cost O(1) on average, the same as HashMap, with a small constant overhead to maintain the insertion-order linked list; the map holds up to n entries.