Open In App

TreeMap in Java

Last Updated : 08 Aug, 2025
Suggest changes
Share
Like Article
Like
Report

TreeMap in Java is an implemented class that extends Map, storing key-value pairs in a sorted order (natural or custom) using a Red-Black Tree. And it ensures O(log n) time for insertion, deletion and Seaching.

Key Features of TreeMap

  • The keys in a TreeMap are always sorted.
  • Most operations, such as get, put and remove, have a time complexity of O(log n).
  • TreeMap does not allow null as a key; it allows null as a value. Attempting to insert a null key will result in a NullPointerException.
  • TreeMap is not synchronized. For thread-safe operations, we need to use Collections. synchronized map.
  • Entry pairs returned by the methods in this class and their views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method.

Example: Java Program to create a TreeMap

Java
import java.util.Map; import java.util.TreeMap; public class TreeMapCreation {  public static void main(String args[])  {  // Create a TreeMap of Strings (keys) and Integers (values)  TreeMap<String, Integer> tm = new TreeMap<>();  System.out.println("TreeMap elements: " + tm);  } } 

Output
TreeMap elements: {} 

Hierarchy of TreeMap

map
Hierarchy-TreeMap

Constructors of TreeMap

In order to create a TreeMap, we need to create an object of the TreeMap class. The TreeMap class consists of various constructors that allow the possible creation of the TreeMap. The following are the constructors available in this class:

1. TreeMap(): This constructor is used to build an empty TreeMap that will be sorted by using the natural order of its keys. 

Syntax:

TreeMap<K, V> map = new TreeMap<>();

Example: Java Program to Demonstrate TreeMap using the Default Constructor

Java
import java.util.*; public class Geeks {  // To show TreeMap constructor  static void Constructor()  {  // Creating an empty TreeMap  TreeMap<Integer, String> tm  = new TreeMap<Integer, String>();  // Mapping string values to int keys using put() method  tm.put(10, "Geeks");  tm.put(15, "For");  tm.put(20, "Geeks");  // Printing the elements of TreeMap  System.out.println("TreeMap: " + tm);  }  public static void main(String[] args)  {  System.out.println(  "TreeMap using TreeMap() constructor");  // Calling constructor  Constructor();  } } 

Output
TreeMap using TreeMap() constructor TreeMap: {10=Geeks, 15=For, 20=Geeks} 


2. TreeMap(Comparator comp): This constructor is used to build an empty TreeMap object in which the elements will need an external specification of the sorting order.

Syntax:

TreeMap<K, V> map = new TreeMap<>(Comparator<? super K> comparator);

Example: Java Program to Demonstrate TreeMap using Comparator Constructor

Java
import java.util.*; class Student {  int rollno;  String name, address;  // Constructor to initialize student details  public Student(int rollno, String name, String address) {  this.rollno = rollno;  this.name = name;  this.address = address;  }  // Override the toString() method to print student details  public String toString() {  return this.rollno + " " + this.name + " " + this.address;  } } // Comparator class to define how to compare two students based on their roll number class SortByRoll implements Comparator<Student> {  public int compare(Student a, Student b) {    // Compare based on roll number  return a.rollno - b.rollno;  } } public class Geeks {  public static void main(String[] args) {    // Create a TreeMap using a Comparator to sort Student objects by roll number  TreeMap<Student, Integer> tm = new TreeMap<>(new SortByRoll());  // Add students to the TreeMap with their roll numbers as keys  tm.put(new Student(111, "Geek1", "New York"), 1);  tm.put(new Student(131, "Geek2", "London"), 2);  tm.put(new Student(121, "Geek3", "Paris"), 3);  // Print the TreeMap, which is automatically sorted by roll number  System.out.println("TreeMap sorted by roll number: " + tm);  } } 

Output
TreeMap sorted by roll number: {111 Geek1 New York=1, 121 Geek3 Paris=3, 131 Geek2 London=2} 


3. TreeMap(Map M): This constructor is used to initialize a TreeMap with the entries from the given map M which will be sorted by using the natural order of the keys.

Syntax:

TreeMap<K, V> map = new TreeMap<>(Map<? extends K, ? extends V> m);

Example: Java Program to Demonstrate TreeMap using the TreeMap(Map M) Constructor

Java
import java.util.*; import java.util.concurrent.*; public class Geeks {  // Method To illustrate constructor<Map>  static void Constructor()  {  // Creating an empty HashMap  Map<Integer, String> m  = new HashMap<Integer, String>();  // Mapping string values to int keys using put() method  m.put(10, "Geeks");  m.put(20, "For");  m.put(30, "Geeks");  // Creating the TreeMap using the Map  TreeMap<Integer, String> tm  = new TreeMap<Integer, String>(  m);  // Printing the elements of TreeMap  System.out.println("TreeMap: " + tm);  }    public static void main(String[] args)  {  System.out.println(  "TreeMap using TreeMap(Map) Constructor");  Constructor();  } } 

Output
TreeMap using TreeMap(Map) Constructor TreeMap: {10=Geeks, 20=For, 30=Geeks} 

Example: Demonstrating TreeMap using the SortedMap Constructor.

Java
import java.util.*; import java.util.concurrent.*; public class Geeks {  // Method To show TreeMap(SortedMap) constructor  static void Constructor()  {  // Creating a SortedMap  SortedMap<Integer, String> sm  = new ConcurrentSkipListMap<Integer,  String>();  // Mapping string values to int keys using put() method  sm.put(10, "Geeks");  sm.put(15, "4");  sm.put(20, "Geeks");  sm.put(25, "Welcomes");  sm.put(30, "You");  // Creating the TreeMap using the SortedMap  TreeMap<Integer, String> tm  = new TreeMap<Integer, String>(  sm);  // Printing the elements of TreeMap  System.out.println("TreeMap: " + tm);  }  public static void main(String[] args)  {  System.out.println(  "TreeMap using TreeMap(SortedMap) constructor");  Constructor();  } } 

Output
TreeMap using TreeMap(SortedMap) constructor TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} 

Performing Various Operations on TreeMap

1. Adding Elements

We can use the put() method to insert elements to a TreeMap. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in ascending order. 

Example: Java Program to insert elements into a TreeMap

Java
import java.util.*; class Geeks {    public static void main(String args[])  {  // Initialization of TreeMap without generics (raw type)  TreeMap<Integer, String> tm = new TreeMap<>();  // Inserting the elements in TreeMap using put() method  tm.put(3, "Geeks");  tm.put(2, "For");  tm.put(1, "Geeks");  // Printing the TreeMap with raw type  System.out.println("TreeMap with raw type: " + tm);  // Initialization of TreeMap with Generics  TreeMap<Integer, String> tm1 = new TreeMap<>();  // Inserting elements into tm1  tm1.put(3, "Language");  tm1.put(2, "Programming");  tm1.put(1, "Java");  // Printing the TreeMap with generics  System.out.println("TreeMap with generics: " + tm1);  } } 

Output
TreeMap with raw type: {1=Geeks, 2=For, 3=Geeks} TreeMap with generics: {1=Java, 2=Programming, 3=Language} 

2. Changing Elements

To change the element in a TreeMap, simply use the put() method again with the same key and the new value.

Example: Java program to Illustrate Updation of Elements in TreeMap using put() Method

Java
import java.util.*; class Geeks {  public static void main(String args[])  {  // Initialization of a TreeMap using Generics  TreeMap<Integer, String> tm  = new TreeMap<Integer, String>();  // Inserting the elements in Map using put() method  tm.put(3, "Geeks");  tm.put(2, "Geeks");  tm.put(1, "Geeks");  // Print all current elements in map  System.out.println(tm);  // Inserting the element at specified corresponding to specified key  tm.put(2, "For");  // Printing the updated elements of Map  System.out.println(tm);  } } 

Output
{1=Geeks, 2=Geeks, 3=Geeks} {1=Geeks, 2=For, 3=Geeks} 

3. Removing Element

We can use the remove() method to remove element from the TreeMap.

Example: Java Program to remove an element from a TreeMap

Java
import java.util.*; class Geeks {  public static void main(String args[])  {  // Initialization of a TreeMap using Generics  TreeMap<Integer, String> tm  = new TreeMap<Integer, String>();  // Inserting the elements using put() method  tm.put(3, "Java");  tm.put(2, "C++");  tm.put(1, "Pyhton");  tm.put(4, "JS");  // Printing all elements of Map  System.out.println(tm);  // Removing the element corresponding to key  tm.remove(4);  // Printing updated TreeMap  System.out.println(tm);  } } 

Output
{1=Pyhton, 2=C++, 3=Java, 4=JS} {1=Pyhton, 2=C++, 3=Java} 

4. Iterating Elements

There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.

Example: Java Program to demonstrates the use of for-each loop to iterate over the elements of a TreeMap.

Java
import java.util.*; class Geeks {  public static void main(String args[])  {  // Initialization of TreeMap  TreeMap<Integer, String> tm = new TreeMap<>();  // Inserting elements  tm.put(3, "Geeks");  tm.put(2, "For");  tm.put(1, "Geeks");  // For-each loop for traversal over entrySet()  for (Map.Entry<Integer, String> e : tm.entrySet()) {  int k = e.getKey();  String v = e.getValue();    // Printing the key and value  System.out.println(k + " : " + v);  }  } } 

Output
1 : Geeks 2 : For 3 : Geeks 

Methods of TreeMap

MethodAction Performed
clear()The method removes all mappings from this TreeMap and clears the map.
clone()The method returns a shallow copy of this TreeMap.
containsKey(Object key)Returns true if this map contains a mapping for the specified key.
containsValue(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a set view of the mappings contained in this map.
firstKey()Returns the first (lowest) key currently in this sorted map.
get(Object key)Returns the value to which this map maps the specified key.
headMap(Object key_value)The method returns a view of the portion of the map strictly less than the parameter key_value.
keySet()The method returns a Set view of the keys contained in the treemap.
lastKey()Returns the last (highest) key currently in this sorted map.
put(Object key, Object value)The method is used to insert a mapping into a map.
putAll(Map map)Copies all of the mappings from the specified map to this map.
remove(Object key)Removes the mapping for this key from this TreeMap if present.
size()Returns the number of key-value mappings in this map.
subMap((K startKey, K endKey)The method returns the portion of this map whose keys range from startKey, inclusive, to endKey, exclusive.
values()Returns a collection view of the values contained in this map.

Explore