Video in progress
How does LinkedHashMap differ from a regular HashMap?
LinkedHashMap returns entries in insertion order, because it threads them together with an extra doubly linked list. HashMap gives no guarantee about iteration order.
📖 Answer
Map<String, Integer> hm = new HashMap<>();
Map<String, Integer> lhm = new LinkedHashMap<>();
for (String k : List.of("zebra", "olma", "kiwi")) {
hm.put(k, k.length());
lhm.put(k, k.length());
}
System.out.println(hm.keySet()); // the order can be anything
System.out.println(lhm.keySet()); // [zebra, olma, kiwi]
The price is two extra references per entry (before, after), so slightly more memory. Speed is practically the same as HashMap.
When you need it: when the order of fields in a JSON response must be preserved, or when you have to show a list to the user in the order they entered it. There is also another mode, "access order", which is how people build an LRU cache.
Asserts in tests that rely on HashMap ordering can break when the Java version changes, which is one more reason to choose LinkedHashMap.
Sign up to mark studied questions and save your progress.