HashMap vs TreeMap vs LinkedHashMap in Java: Key Differences and Usage
HashMap stores key-value pairs with no order and offers fast access, TreeMap keeps keys sorted naturally or by a comparator, and LinkedHashMap maintains insertion order with a linked list. Choose HashMap for speed, TreeMap for sorted keys, and LinkedHashMap when order matters.Quick Comparison
Here is a quick side-by-side comparison of HashMap, TreeMap, and LinkedHashMap based on key factors.
| Feature | HashMap | TreeMap | LinkedHashMap |
|---|---|---|---|
| Ordering | No order (random) | Sorted by keys (natural or comparator) | Insertion order |
| Performance (get/put) | O(1) average | O(log n) | O(1) average |
| Null keys allowed | Yes (one null key) | No | Yes (one null key) |
| Implementation | Hash table | Red-Black tree | Hash table + doubly linked list |
| Use case | Fast access without order | Sorted map needed | Order of insertion matters |
Key Differences
HashMap uses a hash table to store entries, so it provides very fast access and insertion but does not guarantee any order of keys. It allows one null key and multiple null values.
TreeMap stores entries in a red-black tree structure, which keeps keys sorted either by their natural order or a custom comparator. This makes operations slower (logarithmic time) but useful when sorted data is required. It does not allow null keys because sorting null is undefined.
LinkedHashMap combines a hash table with a doubly linked list to maintain the order in which entries were inserted. It offers similar performance to HashMap but preserves insertion order, making it ideal when order matters but sorting is not needed. It also allows one null key.
Code Comparison
This example shows how to add and print entries using HashMap.
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("apple", 3); map.put("banana", 2); map.put("orange", 5); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } } }
TreeMap Equivalent
This example shows the same task using TreeMap, which prints entries sorted by key.
import java.util.Map; import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { Map<String, Integer> map = new TreeMap<>(); map.put("apple", 3); map.put("banana", 2); map.put("orange", 5); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } } }
When to Use Which
Choose HashMap when you need the fastest access and don't care about order. Use TreeMap when you need keys sorted automatically, such as for range queries or ordered iteration. Pick LinkedHashMap when you want to preserve the order of insertion, like caching or predictable iteration order.