HOME HTML EDITOR C JAVA PHP

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?

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

Difference Between HashMap and TreeMap

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.