Learn the differences between TreeMap and HashMap in Java with examples, advantages, and performance insights for efficient data management.
HashMap in Java is a collection class that implements the Map interface. It stores elements as key-value pairs. Each key is unique, and a key maps to exactly one value. HashMap allows one null key and multiple null values. It does not maintain any specific order of elements because it uses a hashing mechanism for fast retrieval.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
map.put(null, "Grapes");
System.out.println("HashMap Elements:");
for (Integer key : map.keySet()) {
System.out.println(key + " => " + map.get(key));
}
}
}
Output:
HashMap Elements: null => Grapes 1 => Apple 2 => Banana 3 => Cherry
TreeMap in Java is another implementation of the Map interface. Unlike HashMap, TreeMap stores elements in a sorted order of keys, either natural ordering or defined by a comparator. It does not allow null keys (throws NullPointerException if used) but allows multiple null values.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "Cherry");
map.put(1, "Apple");
map.put(2, "Banana");
System.out.println("TreeMap Elements:");
for (Integer key : map.keySet()) {
System.out.println(key + " => " + map.get(key));
}
}
}
Output:
TreeMap Elements: 1 => Apple 2 => Banana 3 => Cherry
| Aspect | HashMap | TreeMap |
|---|---|---|
| Order | No guaranteed order of elements. | Maintains sorted order of keys. |
| Null Keys | Allows one null key. | Does not allow null keys. |
| Performance | Faster for insertion, search, and delete operations. | Slower due to sorting overhead. |
| Implementation | Based on Hash Table. | Based on Red-Black Tree. |
| Sorting | Unsorted collection. | Automatically sorted by key. |
HashMap provides faster data access, making it ideal for performance-critical applications where ordering is not required. TreeMap is useful when you need to maintain a sorted map or perform range-based operations. Both classes offer efficient ways to store key-value pairs and are part of the Java Collections Framework.