Java HashMap, LinkedHashMap, and TreeMap – Complete Guide with Examples
Learn Java Map implementations—HashMap, LinkedHashMap, and TreeMap—their differences, features, and how to store and manage key-value pairs efficiently in Java applications.
HashMap, LinkedHashMap, and TreeMap in Java – Complete Detailed Tutorial
The Map interface in Java stores key-value pairs, and its commonly used implementations are HashMap, LinkedHashMap, and TreeMap. Each has different ordering and performance characteristics.
1. HashMap
- Implements Map interface
- Stores key-value pairs
- Keys are unique, values can be duplicated
- No guaranteed order
- Allows one null key and multiple null values
- Backed by hash table, provides fast access
Common Methods:
| MethodDescription | |
| put(K key, V value) | Adds a key-value pair |
| get(Object key) | Retrieves value for a key |
| remove(Object key) | Removes key-value pair |
| containsKey(Object key) | Checks if key exists |
| containsValue(Object value) | Checks if value exists |
| size() | Returns number of entries |
Example – Using HashMap
Output (order may vary):
2. LinkedHashMap
- Extends HashMap, implements Map interface
- Maintains insertion order
- Allows one null key and multiple null values
- Slightly slower than HashMap due to ordering maintenance
Example – Using LinkedHashMap
Output:
Explanation:
- Preserves insertion order
- Useful when order matters
3. TreeMap
- Implements SortedMap interface
- Stores key-value pairs in ascending sorted order by key
- Does not allow null keys, allows multiple null values
- Backed by Red-Black tree
- Slower than HashMap and LinkedHashMap due to sorting overhead
Example – Using TreeMap
Output:
4. HashMap vs LinkedHashMap vs TreeMap
| FeatureHashMapLinkedHashMapTreeMap | |||
| Order | Unordered | Insertion order | Sorted order (ascending) |
| Null Key | Allowed (1) | Allowed (1) | Not allowed |
| Null Value | Allowed | Allowed | Allowed |
| Performance | Fast (O(1)) | Slightly slower | Slower (O(log n)) |
| Implementation | Hash table | Hash table + linked list | Red-Black tree |
5. Key Points
- Choose HashMap for fast access without order
- Choose LinkedHashMap to maintain insertion order
- Choose TreeMap to maintain sorted key order
- All implement Map interface, store key-value pairs, and provide methods like put, get, remove
6. Summary
- HashMap: fast, unordered, allows one null key
- LinkedHashMap: maintains insertion order
- TreeMap: sorted order by keys, no null keys
- Essential for efficient key-value storage in Java applications