Interview Q&A · Java · 3 questions in this topic
Maps: HashMap, LinkedHashMap and SortedMap — Java Interview Q&A
How maps store key-value pairs, and how HashMap, LinkedHashMap and SortedMap differ. Part of Collections Framework · 294 questions in the Java bank.
What is the Map interface?
Answer
Map is an interface for key-value associations where each key maps to exactly one value. Keys must be unique while values may repeat, and lookup, insertion, and removal are keyed operations. Map does not extend Collection because it stores pairs rather than single elements. It exposes three collection views for traversal: keySet for keys, values for values, and entrySet for key-value entries.
Key points
- 1HashMap allows one null key and many null values; ConcurrentHashMap allows neither.
- 2Iteration order is unspecified for HashMap, insertion or access order for LinkedHashMap, and sorted for TreeMap.
- 3Use computeIfAbsent or merge instead of get-then-put to avoid a redundant second lookup.
Example
Map<String, Integer> age = new HashMap<>(); age.put("Ada", 36); for (Map.Entry<String, Integer> e : age.entrySet()) { System.out.println(e.getKey() + "=" + e.getValue()); }
What is LinkedHashMap?
Answer
LinkedHashMap is a HashMap subclass that preserves either insertion order or, optionally, access order for iteration. Access order plus overriding removeEldestEntry gives a compact LRU cache recipe used widely in interviews. Iteration is fast because entries are linked, but insertion and deletion are slightly slower than plain HashMap due to link maintenance. It still allows one null key and multiple null values like HashMap.
Example
Map<String, String> cache = new LinkedHashMap<>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<String, String> e) { return size() > 100; } };
What is SortedMap?
Answer
SortedMap is a Map whose keys stay in ascending order by natural ordering or by a supplied Comparator. It adds boundary operations such as firstKey, lastKey, subMap, headMap, and tailMap for range views. TreeMap is the standard Red-Black tree implementation of this contract. Since Java 6 the NavigableMap interface extends SortedMap with richer navigation such as ceiling, floor, and descending maps, so modern code usually programs to NavigableMap.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission