TreeMap Class in Java

TreeMap Class

The TreeMap class extends the AbstarctMap class and implements the Map interface. It stores value in sorted order. It contains only unique values i.e. duplicate are not allowed

Example: Program to implement methods available in TreeMap class


import java.util.*;
public class TreeMapDemo
{
      public static void main(String args[])
      {
            TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
            System.out.println("Initial size of TreeMap: "+tm.size());
            tm.put(2, "Green");
            tm.put(5, "Red");
            tm.put(3, "Black");
            tm.put(1, "White");
            tm.put(new Integer(7), "Orange");

            // tm.put(08,null); NullPointerException
            Set set = tm.entrySet();
            Iterator i = set.iterator();

            //Retriving the elemnt
            while(i.hasNext())
            {
                   Map.Entry me = (Map.Entry)i.next();
                   System.out.print(me.getKey() + ": ");
                   System.out.println(me.getValue());
            }
            System.out.println ("Size after addtion: "+tm.size());
            tm.remove(3);
            System.out.println ("Size after deletion: "+tm.size());
      }
}


Output:
Initial size of TreeMap: 0
1: White
2: Green
3: Black
5: Red
7: Orange
Size after addtion: 5
Size after deletion: 4