Java TreeMap
TreeMap is a part of the Java Collections Framework.
It stores data in key-value pairs just like HashMap.
TreeMap belongs to the java.util package.
1. Why Use TreeMap?
- Stores data in key-value format.
- Keys are sorted automatically (ascending order).
- No duplicate keys allowed.
- Does not allow null key.
2. Importing TreeMap
import java.util.TreeMap;
3. Creating a TreeMap
TreeMap map = new TreeMap();
4. Adding Elements (put method)
map.put("Banana", 50);
map.put("Apple", 100);
map.put("Mango", 80);
Output will be sorted by keys automatically:
{Apple=100, Banana=50, Mango=80}
5. Accessing Elements (get method)
System.out.println(map.get("Apple"));
6. Removing Elements (remove method)
map.remove("Banana");
7. Checking Key or Value
map.containsKey("Mango");
map.containsValue(100);
8. Looping Through TreeMap
for(String key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
9. Size of TreeMap
System.out.println(map.size());
10. Clear TreeMap
map.clear();
Important Points
- TreeMap maintains sorted order of keys.
- Does not allow null key.
- Values can be duplicate.
- Slower than HashMap (because it maintains sorting).
- Not synchronized (not thread-safe).
Difference Between HashMap and TreeMap
- HashMap does not maintain order.
- TreeMap maintains sorted order.
- HashMap allows one null key.
- TreeMap does not allow null key.
- HashMap is faster.
- TreeMap is slightly slower due to sorting.
Example Program
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap marks = new TreeMap<>();
marks.put("Rahul", 85);
marks.put("Amit", 90);
marks.put("Neha", 88);
for(String name : marks.keySet()) {
System.out.println(name + " : " + marks.get(name));
}
}
}
Conclusion
TreeMap is useful when you need sorted data in key-value format.
It automatically sorts keys and is widely used in applications where order matters.