Java
Data Structures
HashMap
LinkedHashMap
TreeMap

Difference between HashMap, LinkedHashMap and TreeMap

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

HashMap, LinkedHashMap, and TreeMap are three common types of maps used in Java, which are part of the Java Collections Framework. All three classes implement the Map interface but differ in their ordering and the rules they use to store the elements. Understanding the differences between these can help in choosing the appropriate type for specific programming contexts.

1. HashMap

HashMap is the most commonly used Map implementation in Java. It stores its entries in a table format, using a hash function to determine where keys are stored. It doesn't guarantee any order of its entries; thus, the order can change over time.

Technical Details:

  • Hash Function: Keys are hashed to a hash value which is then used to find a bucket where the Entry object (key-value pair) will be stored.
  • Performance: Offers constant time performance for basic operations, i.e., get() and put(), assuming the hash function disperses elements properly among the buckets.

Usage Example:

java
1Map<Integer, String> hashMap = new HashMap<>();
2hashMap.put(1, "Apple");
3hashMap.put(3, "Orange");
4hashMap.put(2, "Banana");
5// Iterating may result in a different order on different runs
6for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
7    System.out.println(entry.getKey() + " -> " + entry.getValue());
8}

2. LinkedHashMap

LinkedHashMap is a subclass of HashMap, with the additional feature of maintaining a linked list running through its entries. This linkage maintains the order of elements as they are inserted into the map. If access order (rather than insertion order) is specified at construction time, the order in which keys are accessed is maintained.

Technical Details:

  • Ordering: Maintains a doubly-linked list across all of its entries to define the iteration ordering.
  • Performance: Slightly slower than HashMap because it maintains a list.

Usage Example:

java
1Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
2linkedHashMap.put(1, "Apple");
3linkedHashMap.put(3, "Orange");
4linkedHashMap.put(2, "Banana");
5// Entries will be printed in the order they were added: Apple, Orange, Banana
6for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {
7    System.out.println(entry.getKey() + " -> " + entry.getValue());
8}

3. TreeMap

TreeMap implements the NavigableMap interface and stores its entries in a red-black tree. This structure guarantees that the elements are sorted by their natural ordering (according to the compareTo() method in their keys) or by a Comparator provided at map creation.

Technical Details:

  • Sorting: Always sorts the keys based on their natural order or a specified Comparator.
  • Performance: Provides guaranteed log(n) time cost for basic operations like get(), put(), and remove().

Usage Example:

java
1Map<Integer, String> treeMap = new TreeMap<>();
2treeMap.put(3, "Orange");
3treeMap.put(1, "Apple");
4treeMap.put(2, "Banana");
5// Entries will be printed in natural order of keys: Apple, Banana, Orange
6for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
7    System.out.println(entry.getKey() + " -> " + entry.getValue());
8}

Comparative Analysis

Below is a table summarizing the key differences:

FeatureHashMapLinkedHashMapTreeMap
Order of elementsNo guaranteed orderInsertion order or access orderSorted by natural order or Comparator
PerformanceConstant time for get() and put()Slightly slower than HashMap due to linked list overheadLogarithmic time for get(), put(), and remove()
Iteration orderRandomPredictableSorted
Null keys/valuesAllows one null key and multiple null valuesAllows one null key and multiple null valuesOnly allows null values if using a custom comparator that handles them

Conclusion

Choosing the correct type of Map implementation depends on the requirements of the application. If ordering isn't an issue, HashMap provides an efficient solution. For predictable iteration order, LinkedHashMap is the suitable option. For automatically sorted keys, one should use TreeMap. Each map comes with its own set of trade-offs in terms of memory usage, performance, and functionality which should be carefully weighed against application needs.


Course illustration
Course illustration

All Rights Reserved.