Java Map Implementations: HashMap vs TreeMap vs LinkedHashMap


Java Map Implementations: HashMap vs TreeMap vs LinkedHashMap

In Java, the Map interface represents a collection of key-value pairs, and it's part of the java.util package. Three commonly used implementations are:

  • HashMap
  • TreeMap
  • LinkedHashMap
βœ… HashMap
  • Implements: Map interface.
  • Ordering: No guaranteed order of keys.
  • Performance: Offers O(1) time complexity for get() and put() operations in average case.
  • Nulls: Allows one null key and multiple null values.
  • Use case: When you don’t care about order and need fast access.
πŸ“Œ Example:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 5);
map.put("cherry", 15);

βœ… TreeMap
  • Implements: NavigableMap, a subtype of SortedMap.
  • Ordering: Keys are stored in sorted (natural or custom) order.
  • Performance: O(log n) time complexity due to use of Red-Black Tree.
  • Nulls: Does not allow null keys (but allows null values).
  • Use case: When you need to maintain sorted order of keys.
πŸ“Œ Example:

Map<String, Integer> map = new TreeMap<>();
map.put("apple", 10);
map.put("banana", 5);
map.put("cherry", 15);
// Output order: apple, banana, cherry

βœ… LinkedHashMap
  • Implements: Map interface.
  • Ordering: Maintains insertion order (can also be access order).
  • Performance: O(1) for get() and put(), similar to HashMap, with slight overhead.
  • Nulls: Allows one null key and multiple null values.
  • Use case: When you need fast access and want to preserve insertion order.
πŸ“Œ Example:

Map<String, Integer> map = new LinkedHashMap<>();
map.put("apple", 10);
map.put("banana", 5);
map.put("cherry", 15);
// Output order: apple, banana, cherry

πŸ” Quick Comparison
Feature HashMap TreeMap LinkedHashMap
Order No order Sorted by key Insertion order
Performance O(1) avg O(log n) O(1) avg
Null Keys 1 allowed ❌ Not allowed 1 allowed
Use case Fast access Sorted map Access + Order