What is HashMap in Java?
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.
Example of HashMap in Java
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));
}
}
}
HashMap Elements: null => Grapes 1 => Apple 2 => Banana 3 => Cherry
What is TreeMap in Java?
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.
Example of TreeMap in Java
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));
}
}
}
TreeMap Elements: 1 => Apple 2 => Banana 3 => Cherry
Differences Between HashMap and TreeMap
| 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. |
Advantages
HashMap provides faster data access (O(1) average), 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 like finding first/last key or sub-maps.
Both classes offer efficient ways to store key-value pairs and are part of the Java Collections Framework with thread-safe alternatives available.