Java Collection Framework


TreeMap class extends 

It is also same as HashMap except it maintains the elements stored in the sorted order.


Declaration of TreeMap class

public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializable

Important points on TreeMap

  • TreeMap stores elements based on key, value pair.
  • All the keys in the TreeMap must be unique. You can insert any number of duplicate values in the key.
  • Null values are not allowed to be stored in TreeMap. As null value cannot be sorted.
  • In TreeMap elements are stored in sorted order. Default sorting is done in ascending order.

Create TreeMap in java

We can use any of the following constructors to create TreeMap based on our needs.

  • TreeMap Map = new TreeMap();
  • TreeMap Map = new TreeMap(Comparator comp);
  • TreeMap Map = new TreeMap(Map m);
  • TreeMap Map = new TreeMap(SortedMap m);

Simple Example

package treeMap;

import java.util.TreeMap;

public class SimpleTreeMap {

    public static void main(String[] args) {
      //create TreeMap
      TreeMap javaRadarMap = new TreeMap();

       //add elements to HashMap
       javaRadarMap.put(1, "Mukesh");
       javaRadarMap.put(3, "Puja");
       javaRadarMap.put(7, "Kavya");
       javaRadarMap.put(5, "Shweta");
       javaRadarMap.put(4, "Rajneesh");
       javaRadarMap.put(2, "Mithilesh");




{1=Mukesh, 2=Mithilesh, 3=Puja, 4=Rajneesh, 5=Shweta, 7=Kavya}

Please Share this page
Views : 90
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!