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 forget()
andput()
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 ofSortedMap
. - 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)
forget()
andput()
, 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 |