Java TreeMap Class


The JavaTreeMap class is a “red-black” tree-based implementation. The TreeMap implements the NavigableMap interface which extends the Sorted Map and the Map interface in turn. TreeMap allows users to store key-value data pairs in a sorted technique.

Features of a TreeMap

  • Values in a TreeMap are dictated by the key. As mentioned above, this class implements the NavigableMap interface and extends the AbstractMap class.
  • Only unique elements are contained in a TreeMap. Duplicate copies are removed.
  • A TreeMap cannot have a null key. However, the values of the elements can be null.
  • TreeMap is non-synchronized
  • The Tree is sorted in the ascending order of keys.

Declaration Syntax

public class TreeMap <K,V> extends AbstractMap <K,V> implements NavigableMap <K,V>, Cloneable, Serializable

The two parameters used here are K and V. While K deals with the types of keys used and maintained in the map, V denotes the values associated with those key values. A key and value always occur in a pair as the key provides identity to the value.


  • TreeMap() – Will construct an empty tree map that will be sorted according to the natural key order.
  • TreeMap (Comparator <? super K> comparator) – Here the comparator will determine how the empty TreeMap will be sorted after construction.
  • TreeMap (Map<? extends K,? extends V>m )- A new TreeMap will be created using the values of m. The map will then be sorted according to the natural key order.
  • TreeMap (SortedMap <K,? extends V> m) – Will construct a new tree map using the values of the sorted map m and according to the same order of the sorted map.


import java.util.*;

class DemoTreeMap
public static void main (String args [])
TreeMap <Integer,String> map = new TreeMap <Integer, String>();


for(Map.Entry m:map.entrySet())



1 Aaron
2 Varun
3 Akshay
4 Rahul


  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.