What is the Difference Between HashMap and TreeMap in Java?
Both implement Map interface (key-value pairs), but differ in ordering, performance, and null handling.
1. HashMap (Hash Table)
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map hashMap = new HashMap<>();
hashMap.put("Banana", 20);
hashMap.put("Apple", 10);
hashMap.put("Cherry", 30);
hashMap.put("Apple", 15); // Overwrites previous value
System.out.println("HashMap (no order): " + hashMap);
// O(1) operations
System.out.println("Value for Apple: " + hashMap.get("Apple"));
System.out.println("Contains key Cherry? " + hashMap.containsKey("Cherry"));
System.out.println("Contains value 20? " + hashMap.containsValue(20));
// Allows one null key and multiple null values
hashMap.put(null, 99);
hashMap.put("Grape", null);
System.out.println("With nulls: " + hashMap);
// Get all keys
Set keys = hashMap.keySet();
System.out.println("Keys: " + keys);
// Get all values
Collection values = hashMap.values();
System.out.println("Values: " + values);
}
}
2. TreeMap (Red-Black Tree)
public class TreeMapExample {
public static void main(String[] args) {
Map treeMap = new TreeMap<>();
treeMap.put("Banana", 20);
treeMap.put("Apple", 10);
treeMap.put("Cherry", 30);
treeMap.put("Date", 25);
// Keys are sorted automatically
System.out.println("TreeMap (sorted): " + treeMap);
// Output: {Apple=10, Banana=20, Cherry=30, Date=25}
// O(log n) operations
System.out.println("First key: " + ((TreeMap) treeMap).firstKey());
System.out.println("Last key: " + ((TreeMap) treeMap).lastKey());
// Navigation methods
System.out.println("Lower key than Cherry: " +
((TreeMap) treeMap).lowerKey("Cherry"));
System.out.println("Higher key than Banana: " +
((TreeMap) treeMap).higherKey("Banana"));
// Submaps
SortedMap subMap = ((TreeMap) treeMap)
.subMap("Apple", "Date");
System.out.println("Submap: " + subMap);
// No null key allowed
// treeMap.put(null, 99); // NullPointerException
}
}
Performance Test
public class MapPerformanceTest {
public static void main(String[] args) {
int size = 100000;
// HashMap test
Map hashMap = new HashMap<>();
long start = System.nanoTime();
for (int i = 0; i < size; i++) {
hashMap.put(i, "Value" + i);
}
long hashPut = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < size; i++) {
hashMap.get(i);
}
long hashGet = System.nanoTime() - start;
// TreeMap test
Map treeMap = new TreeMap<>();
start = System.nanoTime();
for (int i = 0; i < size; i++) {
treeMap.put(i, "Value" + i);
}
long treePut = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < size; i++) {
treeMap.get(i);
}
long treeGet = System.nanoTime() - start;
System.out.println("HashMap put: " + hashPut / 1_000_000 + " ms");
System.out.println("TreeMap put: " + treePut / 1_000_000 + " ms");
System.out.println("HashMap get: " + hashGet / 1_000_000 + " ms");
System.out.println("TreeMap get: " + treeGet / 1_000_000 + " ms");
// HashMap is significantly faster
}
}
LinkedHashMap (Insertion Order)
public class LinkedHashMapExample {
public static void main(String[] args) {
// Maintains insertion order
Map linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("Banana", 20);
linkedHashMap.put("Apple", 10);
linkedHashMap.put("Cherry", 30);
System.out.println("LinkedHashMap (insertion order): " + linkedHashMap);
// Output: {Banana=20, Apple=10, Cherry=30}
// Access order mode (LRU cache)
Map lruCache = new LinkedHashMap<>(16, 0.75f, true);
lruCache.put("A", 1);
lruCache.put("B", 2);
lruCache.put("C", 3);
lruCache.get("A"); // A becomes most recently used
System.out.println("LRU Cache: " + lruCache);
}
}
Comparison Table
| Feature | HashMap | TreeMap |
|---|---|---|
| Ordering | No order | Sorted (natural/comparator) |
| Performance | O(1) get/put/remove | O(log n) get/put/remove |
| Null key | Allowed (one null) | Not allowed |
| Null values | Multiple allowed | Multiple allowed |
| Memory | Less overhead | More overhead (tree) |
| Thread-safe | No (use ConcurrentHashMap) | No |
When to Use Which?
// Use HashMap for: Fast lookups, no ordering needed
Map userCache = new HashMap<>();
// Use TreeMap for: Sorted data, range queries, navigation
TreeMap scoreBoard = new TreeMap<>();
scoreBoard.put("Alice", 95);
scoreBoard.put("Bob", 87);
scoreBoard.put("Charlie", 92);
// Get first and last
System.out.println("Highest score: " + scoreBoard.lastEntry());
System.out.println("Lowest score: " + scoreBoard.firstEntry());
// Range query: get scores between 85 and 100
SortedMap highScores = scoreBoard.tailMap("Bob");
System.out.println("High scores: " + highScores);
// Use LinkedHashMap for: Maintain insertion order
Map requestParams = new LinkedHashMap<>();
requestParams.put("name", "John");
requestParams.put("age", "30");
requestParams.put("city", "NYC");
// Parameters will be iterated in insertion order
Master Java Maps with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
