TreeMap Class

TreeMap Class

In this tutorial, we are going to discuss about TreeMap Class in java. The TreeMap class in Java is a part of the Java Collections Framework and implements the SortedMap interface. It is a red-black tree-based implementation of the Map interface, which means it stores key-value pairs in a sorted order based on the natural ordering of the keys or a custom comparator provided by the user.

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.
Constructors

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);
       
      System.out.println(employees);
   }
}

Output

{Ashok=87, Dillesh=42, Naresh=95, Thiru=29, Vinod=34}

That’s all about the TreeMap class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

TreeMap Class
Scroll to top