TreeMap in Java: The Complete Guide

The elements stored in the TreeMap are sorted according to the keys natural ordering by default. The elements stored in TreeMap are unique. It can have multiple null values, but it does not allow a null key.

TreeMap in Java

Java TreeMap class is used to store items in the form of <key, value> pair. The TreeMap class in java is part of the Java Collection framework. It extends the AbstractMap class and implements the NavigableMap interface. However, it is non-synchronized. Therefore, it is not suitable for multithreaded applications.

The internal structure of a TreeMap contains three variables: Object key, Object value, and boolean color (as TreeMap is based on a red-black tree). It also includes three references that are left, right and parent.

Hierarchy of TreeMap in Java

TreeMap in Java



It will create a TreeMap without having any entries, and sorting will be done using the keys’ natural ordering.

TreeMap(Comparator<? super K> comp)

It will create a TreeMap without having any entries, and sorting will be done according to the specified Comparator.

TreeMap(Map<? extends K, ? extends V> mp)

It will create a TreeMap with Map mp elements, and sorting will be done using the natural ordering of the keys.

TreeMap(SortedMap<K, ? extends V> sm)

It will create a TreeMap having the elements of the given SortedMap, and sorting will be done according to the order of the SortedMap.

Methods of TreeMap

boolean containsKey(Object k)

The containsKey(Object k) method will return true if the given key is present in the TreeMap, otherwise false.

boolean containsValue(Object v)

The containsValue() method will return true if the given value is present in the TreeMap for some key, otherwise false.

Object firstKey()

The firstKey() method returns the first key present in the TreeMap.

Object lastKey()

The lastKey() method returns the last key present in the TreeMap.

Object get(Object k)

The get() method will return the value from the TreeMap, which is mapped by the given key k.

Object remove(Object k)

The remove() method will delete the entry having the key k.

void putAll(Map mp)

The putAll() method will insert all the entries from the given map into the TreeMap.

Set keySet()

The keySet() method will return a Set containing all the keys of the TreeMap.

Set entrySet()

The entrySet() method will return all the <key, value> pairs of this TreeMap as a Set.

int size()

The size() method will return the total number of entries in the TreeMap.

Collection values()

The Collection values() method will return a Collection containing all the values in the TreeMap.

Object clone()

The object clone() method will return a copy of the TreeMap.

void clear()

The void clear() method will remove all the elements (all the <key, value> pairs) from the TreeMap.

SortedMap headMap(Object k)

The SortedMap headMap() method will return a SortedMap containing the elements with key_values (not the value mapped by the key) less than the given key_value k.

Object put(Object k, Object v)

The Object put() method will insert an entry with key k and value v in the TreeMap.

SortedMap submap(K from, K to)

The SortedMap submap() method will return a SortedMap having entries starting from the key ‘from’ up to one less than the key ‘to’ from this TreeMap. The K in the arguments specifies the type of key, i.e., Integer, String, etc.

Object ceilingkey(Object k)

The Object ceilingKey() method will return the smallest key greater than the specified key.

Object lowerkey(Object k)

The Object lowerKey() method will return the greatest key less than specified.

Map.Entry firstEntry()

The Map.Entry firstEntry() method will return the TreeMap entry with the lowest key.

Object replace(Object k, Object v)

The Object replace() method will replace the value of key k with the specified value in TreeSet.

The following program demonstrates the implementation of TreeMap in Java.

import java.util.TreeMap;
import java.util.Set;

class Example1
  public static void main(String[] args)
    //creating an empty TreeMap and inserting the key-value pairs in it
    //key is of Integer type and value is of String type
    TreeMap<Integer,String> details=new TreeMap<>();

    //cretaing a set to store the keys in TreeMap
    Set<Integer> keyVal= details.keySet();

    //printing the keys and values of TreeMap
    for(Integer i: keyVal)
      System.out.println("the value for key: "+i+" is: "+details.get(i));


See the following output.

Java TreeMap Tutorial

This program will demonstrate the implementation of a TreeMap and working of the methods like put(), get(), and keyset().

The following program demonstrates the implementation of TreeMap with the methods like replace(), remove() and entrySet().

See another example.

import java.util.TreeMap;
import java.util.Set;

class Example2
  public static void main(String[] args)
    //creating a TreeMap with city names as key and countries as values
    TreeMap<String,String> sample=new TreeMap<>();
    sample.put("New Delhi","India");

    //checking whether certain keys and values are present in the TreeMap or not
    System.out.println("the TreeMap contains Washington DC as a key? "+sample.containsKey("Washington DC"));
    System.out.println("the TreeMap contains India as a value? "+sample.containsKey("India"));

    //replacing and removing few elements
    sample.replace("London","United Kingdom");

    //creating a set for the entries of TreeMap
    Set s=sample.entrySet();
    System.out.println("\nthe entries in TreeMap are:");

See the following output.

Methods of TreeMap

The following program demonstrates the implementation of TreeMap using a Comparator for sorting it in descending order.

import java.util.TreeMap;
import java.util.Set;
import java.util.Comparator;

class DescendingOrder implements Comparator<Integer>
  //comparing two keys for sorting them in descending order
  public int compare(Integer i1, Integer i2)
    return i2.compareTo(i1);

public class Example3
  public static void main(String[] args)
    //creating a TreeMap and sorting it with the Comparator
    TreeMap<Integer,String> sample=new TreeMap<Integer,String>(new DescendingOrder());

    //creating the set for the keys of TreeMap
    Set<Integer> keyVal=sample.keySet();
    System.out.println("the TreeMap is descending order is: ");
    for(Integer i: keyVal)
      System.out.println("key: "+i+"   value: "+sample.get(i));

See the following example.

Java TreeMap class

In this program, a Comparator is used to sort the elements of the TreeMap in the descending order of its keys.

That’s it for this tutorial.

Leave a Comment

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