TreeMap Class

java.util.TreeMap;
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
The TreeMap class implements the SortedMap interface extends AbstractMap by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. It does not define any additional methods of its own.
TreeMap class features:
  • A TreeMap cannot contain duplicate key.
  • It cantain one null key and contain multiple null value .
  • A tree map guarantees that its elements will be sorted in ascending key order.
  • compateTo() and equals() methods is used for its elements .
  • Data structure is based on Balanced Tree .
Constructor of TreeMap class
  1. public TreeMap( )
  2. public TreeMap(Comparator comp)
  3. public TreeMap(Map m)
  4. public TreeMap(SortedMap sm)
Example of TreeMap class
import java.util.TreeMap; import java.util.Set; import java.util.Iterator; import java.util.Map; public class TreeMapDemo { public static void main(String args[]) { TreeMap tm = new TreeMap(); Set set; Map.Entry m; double bal; tm.put("Sunil",134.34); tm.put("Anand", 1023.22); tm.put("Sanjeev",15678.00); tm.put("Sujeet", 5647.22); // Show all set of Tree Map. set = tm.entrySet(); // get iterator Iterator it=set.iterator(); while(it.hasNext()) { m = (Map.Entry) it.next(); System.out.println(m.getKey() + ": " + m.getValue()); } System.out.println(); // Add 1350.67 into Sunil value bal = ((Double)tm.get("Sunil")).doubleValue(); tm.put("Sunil", new Double(bal+1350.67)); System.out.println("Sunil new Value: " + tm.get("Sunil")); } }
 
Output

Anand: 1023.22
Sanjeev: 15678.0
Sujeet: 5647.22
Sunil: 134.34

Sunil new Value: 1485.01

Download this example
 



 

Latest Tutorial


Most Visited Tutorial