Java HashMap and TreeMap Explained
⏱ Estimated reading time: 2 min
Java provides Map implementations to store key-value pairs, where keys are unique and values can be duplicated. Two widely used Map implementations are HashMap and TreeMap.
1. HashMap
Definition
-
HashMapis a hash table-based implementation of the Map interface. -
Stores data in key-value pairs.
-
Keys must be unique, values can be duplicated.
-
Allows one null key and multiple null values.
Features
-
Does not maintain insertion order.
-
Provides fast access and insertion (O(1) average time).
-
Not synchronized → not thread-safe.
Example:
Output:
2. TreeMap
Definition
-
TreeMapis a Red-Black tree-based implementation of the Map interface. -
Stores key-value pairs in sorted order of keys (natural order or custom comparator).
-
Keys must be unique, values can be duplicated.
Features
-
Maintains ascending key order.
-
Slower than HashMap for insertion and access (O(log n)).
-
Does not allow null keys (but allows null values).
Example:
Output:
3. Comparison: HashMap vs TreeMap
| Feature | HashMap | TreeMap |
|---|---|---|
| Order | No guaranteed order | Keys sorted in ascending order |
| Implementation | Hash table | Red-Black tree |
| Performance | Faster (O(1) avg) | Slower (O(log n)) |
| Null Key | Allows one null key | Not allowed |
| Null Value | Allows null values | Allows null values |
| Use Case | Fast lookup and insertions | Sorted key-value pairs |
4. Key Points
-
Both HashMap and TreeMap implement the Map interface.
-
HashMap is preferred for fast access.
-
TreeMap is preferred when sorted keys are required.
-
Both allow duplicate values but unique keys.
5. Conclusion
HashMap and TreeMap are powerful Map implementations in Java. Choosing the right Map depends on requirement: use HashMap for fast access and TreeMap for sorted key-value storage. Understanding their differences ensures efficient and reliable Java applications.
Register Now
Share this Post
← Back to Tutorials