- The - java.util.TreeMapclass implements the- Mapinterface using a balanced binary search tree ordered by keys. In general, any- Comparableobjects may be placed into a- TreeMapas the key. This guarantees that the keys will be in ascending order, as determined by the key object’s- compareTomethod.
 
- 
        Because of the balanced binary tree implementation, the TreeMapclass provides an O(log n) run time for the operationsput,get, andcontainsKey.
 
- 
    The following code fragment demonstrates implementation of a TreeMap:
 TreeMap studentMap = new TreeMap();
 for (int recNum = 1; recNum <= NUM_STUDENTS; recNum++){
 Student s = new Student();    // declare a new Student
 s.setName(...);               // set the student’s
 // attributes
 s.setGradeLevel(...);         // ...
 s.setID(...);                 // ...
    studentMap.put(s.getID(), s); // add student to the map
 // using ID as the key
 }
 // Display the student whose key is S964413
 System.out.println(studentMap.get("S964413"));
 
- 
    The Map interface does not specify a method for obtaining an iterator, and the TreeMapclass does not have one. Instead, you can get the set of all keys by calling thekeySetmethod, then iterate over that set togetall values. For example:
 TreeMap acronym = new TreeMap();
 String key;
 Definition value; // acronym definition
 acronym.put("CS", new Definition("Computer Science"));
 acronym.put("AP", new Definition("Advanced Placement"));
 Set keys = acronym.keySet();
 Iterator iter = keys.iterator();
 while (iter.hasNext()){
 key = (String)iter.next();
 value = (Definition)acronym.get(key);
    // process value
 System.out.println(key + " stands for " +
 value.getDefinition());
 }
 The output for this code fragment is AP stands for Advanced Placement
 CS stands for Computer Science
 The values will be processed in the ascending order of keys. 
- 
  TreeMapis more general thanTreeSet. Both implement Binary Search Trees, but inTreeSetthe values are compared to each other, while inTreeMap, no ordering is assumed for the values and the tree is arranged according to the order of the keys. In a way, a set is a special case of a map where a value serves as its own key.
 
 import java.util.TreeMap;
 
 TreeMap <Integer, String> map = new TreeMap <Integer, String> ();
 String name = "John";
 map.put(new Integer(3),name);
 map.put(new Integer(2),"Nancy");
 map.put(new Integer(1),"George");
 
 System.out.println(“Size of map” + map.size());
 System.out.println(“Person for 1: ” + map.get(1));