TreeMap Class

  • The underlying data structure is RED-BLACK Tree.
  • Duplicate keys are not allowed but values can be duplicated.
  • Insertion order is not preserved and all entries will be inserted according to some sorting order of keys.
  • If we are depending on default natural sorting order keys should be homogeneous and Comparable otherwise we will get ClassCastException.
  • If we are defining our own sorting order by Comparator then keys can be heterogeneous and non Comparable.
  • There are no restrictions on values they can be heterogeneous and non Comparable.
  • For the empty TreeMap as first entry null key is allowed but after inserting that entry if we are trying to insert any other entry we will get NullPointerException.
  • For the non empty TreeMap if we are trying to insert an entry with null key we will get NullPointerException.
  • There are no restrictions for null values.

1. TreeMap t=new TreeMap();

For default natural sorting order.

2. TreeMap t=new TreeMap(Comparator c);

For customized sorting order.

3. TreeMap t=new TreeMap(SortedMap m);

TreeMap t=new TreeMap(Map m);

package com.ashok.collections;

import java.util.TreeMap;

 * @author ashok.mariyala
public class MyTreeMap {
   public static void main(String[] args) {
      TreeMap employees = new TreeMap();

      employees.put("Ashok", 87);
      employees.put("Vinod", 34);
      employees.put("Dillesh", 42);
      employees.put("Thiru", 29);
      employees.put("Naresh", 95);


{Ashok=87, Dillesh=42, Naresh=95, Thiru=29, Vinod=34}
TreeMap Class
Scroll to top