Table of contents
1.
Introduction
1.1.
Declaration
1.2.
Initialization
2.
Hierarchy of TreeMap in Map Interface
3.
Features of TreeMap in Java
4.
Internal Working of Java TreeMap
5.
Constructors TreeMap in Java
6.
Methods of Java TreeMap Class
7.
Basic Operations on TreeMap
7.1.
Java
8.
Navigation Operations on TreeMap
8.1.
Java
8.2.
Java
9.
Advantages of TreeMap in Java
10.
Disadvantages of TreeMap in Java
11.
Frequently Asked Questions
11.1.
What is the SortedMap interface, and how is it different from TreeMap?
11.2.
Is TreeMap ordered in Java?
11.3.
Does TreeMap allow null keys?
11.4.
What is the difference between TreeMap and TreeSet in Java?
11.5.
Can TreeMap have duplicate values?
12.
Conclusion
Last Updated: Dec 19, 2024
Easy

TreeMap in Java

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A tree is a well-known data structure used to organise and represent hierarchical data. It is a collection of objects, known as nodes, linked together in a non-linear manner. A red-black tree is a self-balancing binary search tree in which every path from a node to any of its descendent null nodes should have the same number of black nodes.

A TreeMap is a red-black tree based NavigableMap implementation. The Navigable Map Interface is a member of the Java Collections framework and an extension of the SortedMap class that provides convenient navigation methods to traverse a map. TreeMap also implements the Map interface and the AbstractMap class.

TreeMap in Java

Declaration

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

Initialization

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

 

K - Key object type   V - Value object type

Hierarchy of TreeMap in Map Interface

Hierarchy of TreeMap in Map Interface

Features of TreeMap in Java

  • TreeMap contains key-value mappings sorted in the natural ordering of their keys by default. The mappings can also be sorted using a comparator at map creation time.
  • TreeMap implementation is not synchronised, i.e. if multiple threads access a Map concurrently where at least one thread makes structural modifications, it must be synchronised externally.
  • TreeMap allows the use of null values but not null keys.
  • Its implementation has a time cost of log(n) on all insertion, deletion and access operations.
  • It does not support the Entry.setValue method. All entry pairs returned by methods in this class represent the mappings at the time they were produced.

Internal Working of Java TreeMap

  1. Data Structure: Implemented as a Red-Black Tree (self-balancing binary search tree).
  2. Key-Value Pairs: Stores data in key-value pairs, where keys are unique.
  3. Ordering: Keys are sorted in their natural order or by a custom comparator.
  4. NavigableMap Interface: Implements NavigableMap, allowing operations like ceiling(), floor(), etc.
  5. Complexity: Most operations like put(), remove(), get() have O(log n) time complexity.
  6. Red-Black Tree Properties: Ensures balanced tree structure for efficient search, insertion, and deletion.

Constructors TreeMap in Java

1. TreeMap()

It constructs a new, empty treemap with the natural ordering of its keys.

TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>();

 

2. TreeMap(Comparator<? super K> comparator)

It constructs a new, empty treemap, whose keys are ordered according to the given comparator.

import java.util.*;
import java.util.concurrent.*;
// Comparator implementation
class Sort_keys implements Comparator<K> 
{
     // Comparator code
}
// Main class
public class Main 
{
    public static void main(String[] args)
    {
       TreeMap<K, V> tree_map = new TreeMap<K, V>(new Sort_keys());
     }
}

 

3. TreeMap(Map<? extends K,? extends V> m)

It constructs a new tree map containing the same mappings as the given map, with the natural ordering of its keys.

import java.util.*;
public class Main 
{
public static void main(String[] args)
   {
      Map<Integer, String> hash_map  = new HashMap<Integer, String>();

      // code to perform operations on hash_map

      TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(hash_map);
    }
}

 

4. TreeMap(SortedMap<K,? extends V> m)

It constructs a new tree map containing the same mappings and ordering as the specified sorted map.

import java.util.*;
import java.util.concurrent.*;
public class Main 
{
public static void main(String[] args)
   {
     SortedMap<Integer, String> sorted_map  = new ConcurrentSkipListMap<Integer, String>();


     // code to perform operations on sorted_map


     TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(sorted_map);
   }
}

Methods of Java TreeMap Class

Method

Type

Description

clear()voidIt removes all the mappings from a specified map.
clone()ObjectIt returns a shallow copy of the identity hash map but does not clone its key-value pairs.
containsKey(Object Key)

boolean

 

It returns true if the given object is a key in the map.
containsValue(Object value)It returns true if the given object is mapped to one or more keys in the map.
entrySet()Set<Map.Entry<K, V>>It returns a set-view of all the mappings present in the map.
forEach(action)voidIt performs a given action for each key-value pair.
get(Object key)VIt returns the value of the given key if it is present in the map else, it returns null.
keySet()KeySetView<K, V>It returns a set-view of the keys present in the map
put(K key, V value)VIt adds a key-value pair to the identity hash map. If the key already exists, then its value is updated.
putAll(Map m) voidIt copies all the key-value mappings of a given map and replaces the original content of the map
remove(Object key)VIt removes the mapping for a given key if it is present in the map.
replace(K key,V value)VIt replaces the value of a given key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue)booleanIt replaces the value of a given key only if it is currently mapped to the specified value.
replaceAll(function)voidIt replaces the values of every key with a value generated by a given function.
size()intIt returns the number of key-value pairs in the identity hash map.
values()Collection<V>It returns a collection view of the values present in the map.
ceilingEntry(K key)Map.Entry<K, V>It returns the mapping associated with the least key greater than or equal to the given key or null if absent.
ceilingKey(K key)KIt returns the least key greater than or equal to the given key or null if absent.
comparator()Comparator<? super K>It returns the comparator used to order the keys in the TreeMap.
descendingKeySey()NavigableSet<K>It returns a reverse order of the NavigableSet view of keys in the map.
navigableKetSet()NavigableSet<K>It returns a NavigableSet view of all the keys in the map.
descendingMap()NavigableMap<K,V>It returns a reverse order view of all mappings in the map.
firstEntry()Map.Entry<K, V>It returns the mapping associated with the least key in the map.
firstKey()KIt returns the first key in the map.
floorEntry(K key)Map.Entry<K, V>It returns the mapping associated with the greatest key less than or equal to the given key or null if absent.
floorKey(K key)KIt returns the greatest key less than or equal to the given key or null if absent.
headMap(K toKey)SortedMap<K, V>It returns a portion of the map whose keys are strictly less than the given key, excluding the key itself.
higherEntry(K key)Map.Entry<K, V>It returns the mapping associated with the least key strictly greater than the given key or null if absent.
higherKey(K key)KIt returns the least key strictly greater than the given key or null if absent.
lastEntry()Map.Entry<K, V>It returns the mapping associated with the greatest key in the map.
lastKey()KIt returns the last key in the map.
lowerEntry<K key)Map.Entry<K, V>It returns the mapping associated with the greatest key strictly less than the given key or null if absent.
lowerkey(K key)KIt returns the greatest key strictly less than the given key or null if absent.
pollFirstEntry()

Map.Entry<K, V>

 

It removes and returns the mapping associated with the least key in the map, or null is absent.
pollLastEntry()It removes and returns the mapping associated with the greatest key in the map, or null is absent.
subMap(K keyA, K keyB)

SortedMap<K, V>

 

It returns the map portion containing mappings whose keys range from keyA to keyB, including keyA but excluding keyB.
tailMap(K keyA)It returns the mappings of keys greater than keyA and keyA itself.

Also see,  Swap Function in Java

Basic Operations on TreeMap

  • Adding elements using put() and putAll() functions.
  • Removing elements using remove() function.
  • Accessing elements using entrySet(), values(), keySet() and get() functions.
  • Replacing elements using replace() and replaceAll() functions.
  • Java

Java

import java.util.TreeMap;

public class Main
{
public static void main(String[] args)
    {
TreeMap<String, String> India = new TreeMap<>();

// Adding or insertion
India.put("India","New Delhi");

     TreeMap<String, String> country = new TreeMap<>();
     country.putAll(India);

country.put("Australia","Canberra");
country.put("Germany","Berlin");
country.put("France", "London");

// Accessing elements
System.out.println("TreeMap of country-capital: " + country.entrySet());
System.out.println("\nList of keys (Country): " + country.keySet());
System.out.println("List of values (Capitals): " + country.values());
System.out.println("\nThe capital of France is :" + country.get("France"));
System.out.println();

// Replacing elements
country.replace("France","Paris");
System.out.println("Correcting the capital the of France to " + country.replace("France","Paris"));
System.out.println(country);
System.out.println("\nAbbreviating the names of all capitals.");
country.replaceAll((key , oldValue) -> oldValue.substring(0, 3));
System.out.println(country + "\n");

//Removing elements
System.out.println("Removing Australia: " + country.remove("Australia"));
System.out.println(country);
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

TreeMap of country-capital: [Australia=Canberra, France=London, Germany=Berlin, India=New Delhi]

List of keys Country): [Australia, France, Germany, India]
List of values (Capitals): [Canberra, London, Berlin, New Delhi]

The capital of France is :London

Correcting the capital the of France to Paris
{Australia=Canberra, France=Paris, Germany=Berlin, India=New Delhi}

Abbreviating the names of all capitals.
{Australia=Can, France=Par, Germany=Ber, India=New}

Removing Australia: Can
{France=Par, Germany=Ber, India=New}

Navigation Operations on TreeMap

  • Obtain first and last mappings or keys.
  • Obtain highest and lowest mappings or keys.
  • Use of ceiling and floor methods.
  • Use of pollFirstEntry() and pollLastEntry() methods.    
  • Java

Java

import java.util.TreeMap;

public class Main
{
public static void main(String[] args)
    { 
TreeMap<String, String> country = new TreeMap<>();

country.put("India","New Delhi");
country.put("Australia","Canberra");
country.put("Germany","Berlin");
country.put("France", "Paris");
country.put("Japan", "Tokyo");
country.put("Russia", "Moscow");
country.put("Brazil", "Brasilia");

System.out.println("TreeMap contents: " + country);

// First and last
System.out.println("First key: " + country.firstKey());
System.out.println("First entry " + country.firstEntry());
System.out.println("Last key " + country.lastKey());
System.out.println("Last entry :" + country.lastEntry());
System.out.println();

// Highest and lowest
System.out.println("Higher key: " + country.higherKey("Japan"));
System.out.println("Higher entry: " + country.higherEntry("Japan"));
System.out.println("Lower key: " + country.lowerKey("Japan"));
System.out.println("Lower entry: " + country.lowerEntry("Japan"));
System.out.println();

//Ceiling and floor
System.out.println("Ceiling key: " + country.ceilingKey("Japan"));
System.out.println("Ceiling entry: " + country.ceilingEntry("Japan"));
System.out.println("Floor key: " + country.floorKey("Japan"));
System.out.println("Floor entry: " + country.floorEntry("Japan"));
System.out.println();

// poll first and last entry
System.out.println("Poll first entry: " + country.pollFirstEntry());
System.out.println("Poll last entry: " + country.pollLastEntry());
System.out.println(country);
System.out.println();
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

TreeMap contents: {Australia=Canberra, Brazil=Brasilia, France=Paris, Germany=Berlin, India=New Delhi, Japan=Tokyo, Russia=Moscow}
First key: Australia
First entry Australia=Canberra
Last key Russia
Last entry :Russia=Moscow

Higher key: Russia
Higher entry: Russia=Moscow
Lower key: India
Lower entry: India=New Delhi

Ceiling key: Japan
Ceiling entry: Japan=Tokyo
Floor key: Japan
Floor entry: Japan=Tokyo

Poll first entry: Australia=Canberra
Poll last entry: Russia=Moscow
{Brazil=Brasilia, France=Paris, Germany=Berlin, India=New Delhi, Japan=Tokyo}

 

  • Use of headMap(), tailMap() and subMap() functions.
  • Java

Java

import java.util.TreeMap;

public class Main
{
public static void main(String[] args)
{
TreeMap<String, String> country = new TreeMap<>();

country.put("India","New Delhi");
country.put("Australia","Canberra");
country.put("Germany","Berlin");
country.put("France", "Paris");
country.put("Japan", "Tokyo");
country.put("Russia", "Moscow");
country.put("Brazil", "Brasilia");

System.out.println("TreeMap contents: " + country);

// First and last
System.out.println("\nHeadMap: " + country.headMap("Germany"));
System.out.println("\nTailMap: " + country.tailMap("Germany"));
System.out.println("\nSubMap: " + country.subMap("Germany","Japan"));
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

TreeMap contents: {Australia=Canberra, Brazil=Brasilia, France=Paris, Germany=Berlin, India=New Delhi, Japan=Tokyo, Russia=Moscow}

HeadMap: {Australia=Canberra, Brazil=Brasilia, France=Paris}

TailMap: {Germany=Berlin, India=New Delhi, Japan=Tokyo, Russia=Moscow}

SubMap: {Germany=Berlin, India=New Delhi}

Advantages of TreeMap in Java

  1. Sorted Order: Automatically maintains keys in natural or custom order, making it ideal for applications requiring sorted data.
  2. Efficient Search: Red-Black Tree structure offers O(log n) time complexity for get(), put(), and remove().
  3. NavigableMap Interface: Implements the NavigableMap interface, supporting efficient navigation methods like ceiling(), floor(), higher(), and lower().
  4. No Duplicates: Ensures uniqueness of keys, providing a reliable map structure where duplicate keys are not allowed.
  5. Range Views: Allows operations like subMap(), headMap(), and tailMap() for efficient range querying.
  6. Thread Safety: While not synchronized, individual operations on TreeMap are thread-safe when accessed by a single thread.
  7. Flexible Sorting: Can use a custom comparator for sorting keys, offering flexibility for complex ordering.

Disadvantages of TreeMap in Java

  1. Slower than HashMap: Due to sorting and balancing, TreeMap operations (like put() and get()) are slower (O(log n)) compared to HashMap (O(1) average).
  2. No Null Keys: TreeMap does not allow null keys, unlike HashMap, which can store null values.
  3. Memory Overhead: The Red-Black Tree structure requires extra memory for tree nodes and balancing information.
  4. Not Synchronized: By default, TreeMap is not thread-safe for concurrent modifications. External synchronization is needed in multi-threaded environments.
  5. Comparator Dependency: If the comparator is not provided, the natural ordering of keys must be consistent, which might not always be desirable.
  6. Performance with Large Data: Performance may degrade with very large datasets, as balancing the tree requires more time compared to other structures.

Frequently Asked Questions

What is the SortedMap interface, and how is it different from TreeMap?

The SortedMap interface provides a natural ordering of its keys for easy traversal. Its parent interface is the Map interface, and its subinterface is the NavigableMap.

SortedMap cannot be used to create objects as it is an interface. The implementation of the sortedMap is the TreeMap using which objects can be created. While the SortedMap restricts the use of null keys and null values, the TreeMap imposes restrictions only on the use of null keys.

Is TreeMap ordered in Java?

Yes, TreeMap is ordered. It stores keys in their natural order or according to a custom comparator provided at the time of creation.

Does TreeMap allow null keys?

No, TreeMap does not allow null keys. It throws a NullPointerException if you attempt to insert a null key.

What is the difference between TreeMap and TreeSet in Java?

TreeMap stores key-value pairs, while TreeSet stores only unique keys. Both use a Red-Black Tree, but TreeMap maps keys to values, whereas TreeSet only maintains unique keys.

Can TreeMap have duplicate values?

Yes, TreeMap allows duplicate values but not duplicate keys. The values can be repeated, but each key must be unique.

Conclusion

TreeMaps are special and extremely useful. The mappings they store can be arranged in the ascending order of its keys or by using the comparator as discussed. Since the mappings are already sorted, they quickly access its key-value pairs. This blog explains the TreeMap class in detail, along with its features and constructors. It also lists out the various functions and methods provided by this class to work with key-value mappings. 

Check out this problem - Reverse Nodes In K Group

Recommended Articles:

Live masterclass