Junior — Middle
How do SortedMap and LinkedHashMap data structures differ in Java?
sobes.tech AI
Answer from AI
SortedMap and LinkedHashMap are two implementations of the Map interface in Java, which differ in the order of element storage and internal structure.
-
SortedMap (for example, TreeMap) stores elements in sorted order by key. Keys must be either Comparable or a Comparator must be provided. This allows for quick retrieval of elements in sorted order.
-
LinkedHashMap maintains the order of insertion (or access order if access-order is enabled). This is useful when the order of adding elements is important.
Example:
Map<String, Integer> sortedMap = new TreeMap<>();
sortedMap.put("banana", 2);
sortedMap.put("apple", 5);
sortedMap.put("orange", 3);
System.out.println(sortedMap); // {apple=5, banana=2, orange=3} - sorted by key
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("banana", 2);
linkedHashMap.put("apple", 5);
linkedHashMap.put("orange", 3);
System.out.println(linkedHashMap); // {banana=2, apple=5, orange=3} - insertion order
Summary:
- SortedMap — sorts by key.
- LinkedHashMap — maintains insertion or access order.