Map Implementations in Java
Understanding HashMap, LinkedHashMap, TreeMap, and Hashtable
What are Map Implementations?
Map implementations in Java store key-value pairs, allowing you to quickly retrieve values using their associated keys. Each implementation differs in ordering behavior, null handling, and thread-safety. Understanding these differences helps you choose the right Map for your application.
HashMap
Simple explanation
- •Stores key–value pairs
- •Fast lookup
- •No order guaranteed
Example
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
System.out.println(map);
// Example output (order random): {2=Banana, 1=Apple, 3=Cherry}LinkedHashMap
Simple explanation
- •Same as HashMap, but keeps the insertion order
Example
Map<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
System.out.println(map);
// Output: {1=Apple, 2=Banana, 3=Cherry}TreeMap
Simple explanation
- •Stores keys in sorted (ascending) order
- •Sorting happens automatically
Example
Map<Integer, String> map = new TreeMap<>();
map.put(3, "Cherry");
map.put(1, "Apple");
map.put(2, "Banana");
System.out.println(map);
// Output: {1=Apple, 2=Banana, 3=Cherry} (sorted by key)Hashtable
Simple explanation
- •Like HashMap, but thread-safe
- •Legacy (old), rarely used now
- •Does NOT allow null keys or values
Example
Map<Integer, String> map = new Hashtable<>();
map.put(1, "Apple");
map.put(2, "Banana");
System.out.println(map);
// Output: {2=Banana, 1=Apple}Quick Summary Table
| Map Type | Order? | Allows null? | Thread-safe? | Notes |
|---|---|---|---|---|
| HashMap | No order | Yes | No | Fast, most used |
| LinkedHashMap | Insertion order | Yes | No | Predictable order |
| TreeMap | Sorted by key | No (rare cases) | No | Uses Red-Black Tree |
| Hashtable | No order | No | Yes | Old, replaced by ConcurrentHashMap |
Key Differences at a Glance
HashMap
•Fastest
•Random order
•Allows null
LinkedHashMap
•Insertion order
•Predictable
•Allows null
TreeMap
•Auto-sorted
•By key
•No null keys
Hashtable
•Thread-safe
•Legacy
•No nulls
When to Use Each Map?
Use HashMap when:
You need fast lookups and don't care about order
Use LinkedHashMap when:
You need to maintain insertion order while still having fast access
Use TreeMap when:
You need keys automatically sorted in ascending order
Use Hashtable when:
You're working with legacy code (otherwise use ConcurrentHashMap for thread-safety)
