Java Program to demonstrate the use of TreeMap.
Objective
Write a Java program to store and traverse Key-Value pairs using a TreeMap.
Algorithm / Approach
- Create a
TreeMap. - Use
put(key, value)to insert Roll Numbers (Strings) as keys and Names as values. - Retrieve a specific value using
stud.get("1786"). - Extract all keys using
stud.keySet()into aSet. - Iterate through the keys using an Iterator, and use
get(key)to print the corresponding values.
Test.java
import java.util.*;
class Test {
public static void main(String[] a)
{
TreeMap stud = new TreeMap();
stud.put("1001","Alok");
stud.put("1005","Deepu");
stud.put("1002","Anup");
stud.put("1014","Ayan");
stud.put("1049","Daneyal");
stud.put("1786","Faiz");
System.out.print("Student at 1786- ");
System.out.println(stud.get("1786"));
System.out.println("Traversing...");
Set keys = stud.keySet();
Iterator i = keys.iterator();
while(i.hasNext()) {
String x =(String) i.next();
System.out.println(x+"- ");
System.out.println(stud.get(x));
}
}
}
Expected Output
Student at 1786- Faiz Traversing... 1001- Alok 1002- Anup 1005- Deepu 1014- Ayan 1049- Daneyal 1786- Faiz
Explanation of the Program
- The
Mapinterface is not a true Collection; it stores data in Key-Value pairs (like a dictionary in Python). Keys must be absolutely unique, but values can be duplicated. - A
TreeMapspecifically sorts the entries automatically based on the natural order of the KEYS. - Even though we inserted the Roll Numbers randomly (1001, 1005, 1002), when we iterate over the
keySet(), they are retrieved in perfect numerical order.
Complexity
Time Complexity
O(log n) - For put, get, and remove operations.
Space Complexity
O(n)