TreeMap in Java is an implementation of the NavigableMap interface and extends AbstractMap. It stores key-value pairs in a sorted order based on the natural ordering of keys or a custom Comparator provided at the time of creation. TreeMap is implemented as a red-black tree, which provides guaranteed log(n) time complexity for most operations like put, get, and remove, making it efficient for scenarios where elements need to be sorted.
import java.util.TreeMap;
import java.util.Map;
public class TreeMapExample {
public static void main(String[] args) {
// Creating a TreeMap to store student names and their roll numbers
TreeMap<String, Integer> studentMap = new TreeMap<>();
// Adding students to the TreeMap
studentMap.put("Paani", 101);
studentMap.put("Mahesh", 102);
studentMap.put("Datta", 103);
studentMap.put("Ganesh", 104);
studentMap.put("Harsha", 105);
// Displaying the TreeMap
System.out.println("TreeMap of students:");
System.out.println(studentMap);
// Removing a student from the TreeMap
Integer removedRollNumber = studentMap.remove("Datta");
System.out.println("\nRemoved student 'Datta' with roll number: " + removedRollNumber);
// Displaying the updated TreeMap
System.out.println("\nUpdated TreeMap of students:");
System.out.println(studentMap);
// Checking if a student exists in the TreeMap
String searchStudent = "Harsha";
boolean containsStudent = studentMap.containsKey(searchStudent);
System.out.println("\nDoes the TreeMap contain student '" + searchStudent + "'? " + containsStudent);
// Iterating over the entries of the TreeMap
System.out.println("\nIterating over TreeMap entries:");
for (Map.Entry<String, Integer> entry : studentMap.entrySet()) {
System.out.println("Student: " + entry.getKey() + ", Roll Number: " + entry.getValue());
}
// Size of the TreeMap
System.out.println("\nSize of the TreeMap: " + studentMap.size());
// Clearing the TreeMap
studentMap.clear();
System.out.println("\nIs the TreeMap empty now? " + studentMap.isEmpty());
}
}
D:\>javac TreeMapExample.java
D:\>java TreeMapExample
TreeMap of students:
{Datta=103, Ganesh=104, Harsha=105, Mahesh=102, Paani=101}
Removed student 'Datta' with roll number: 103
Updated TreeMap of students:
{Ganesh=104, Harsha=105, Mahesh=102, Paani=101}
Does the TreeMap contain student 'Harsha'? true
Iterating over TreeMap entries:
Student: Ganesh, Roll Number: 104
Student: Harsha, Roll Number: 105
Student: Mahesh, Roll Number: 102
Student: Paani, Roll Number: 101
Size of the TreeMap: 4
Is the TreeMap empty now? true
Code language: JavaScript (javascript)
TreeMap in Java is a powerful data structure for scenarios where elements need to be stored in a sorted order based on keys. It provides efficient operations for inserting, accessing, and removing elements, making it suitable for applications where sorted mappings are required. Understanding how to effectively use TreeMap allows developers to design efficient algorithms and manage data structures effectively in Java applications.