HashMap and TreeMap are both implementations of the Map interface used to store key-value pairs. The main difference is that HashMap stores entries without maintaining any order, while TreeMap automatically keeps entries sorted based on their keys. HashMap generally offers faster performance, whereas TreeMap is preferred when sorted data is required.
Internal Implementation
Ordering
No ordering guarantee.
{103=Mike, 101=John, 102=David}
Output order may vary.
Automatically sorts keys.
{101=John, 102=David, 103=Mike}
Time Complexity
Null Handling
HashMap<String, String> map =
new HashMap<>();
map.put(null, "Java");
Valid.
TreeMap<String, String> map =
new TreeMap<>();
map.put(null, "Java");Throws NullPointerException.
Sorting Support
Suppose we are storing employee records.
Use HashMap.
Use TreeMap.
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Demo {
public static void main(String[] args) {
Map<Integer, String> hashMap =
new HashMap<>();
hashMap.put(103, "Mike");
hashMap.put(101, "John");
hashMap.put(102, "David");
Map<Integer, String> treeMap =
new TreeMap<>();
treeMap.put(103, "Mike");
treeMap.put(101, "John");
treeMap.put(102, "David");
System.out.println(hashMap);
System.out.println(treeMap);
}
}Order not guaranteed
{101=John, 102=David, 103=Mike}
When to Use HashMap?
When to Use TreeMap?
Comparison Table
Feature HashMap TreeMap
Ordering No Sorted by Key
Internal Structure Hash Table Red-Black Tree
Insertion O(1) O(log n)
Retrieval O(1) O(log n)
Deletion O(1) O(log n)
Null Key One Allowed Not Allowed
Null Values Allowed Allowed
Sorting Support No Yes
A concise interview answer is
HashMap stores key-value pairs without maintaining any order and provides O(1) average-time performance using hashing. TreeMap stores entries in sorted key order using a Red-Black Tree and provides O(log n) performance for insertion, retrieval, and deletion. Use HashMap when speed is important and TreeMap when sorted data is required.
Last updated: 11 November 2026
Previous question: How do you choose the appropriate design pattern for a particular problem in Java?
Next question: When would you use a TreeMap instead of a HashMap?