Java TreeMap

Introduction

The Java TreeMap class is a popular implementation of the Map interface in the Java Collections Framework. It stores data as key-value pairs while automatically keeping the keys in sorted order.

The TreeMap class belongs to the java.util package and is internally implemented using a Red-Black Tree, which is a self-balancing binary search tree. This allows TreeMap to provide efficient insertion, deletion, and searching operations with a time complexity of O(log n).

A TreeMap does not allow duplicate keys, but it allows duplicate values. It also does not allow null keys because keys need to be compared while maintaining the sorted order. However, it allows multiple null values.

What is Java TreeMap?

A TreeMap is a collection that stores key-value pairs in sorted order of keys.

  • Each key must be unique.
  • Duplicate values are allowed.
  • Keys are automatically sorted.
  • Custom sorting can be achieved using a Comparator.

Example:

Key Value
101 Rahul
102 Amit
103 Neha

Output:

101=Rahul
102=Amit
103=Neha

Notice that the keys are sorted automatically.

Java TreeMap Hierarchy

<code class="language-java
   │
AbstractMap
   │
TreeMap

The TreeMap class implements the following interfaces:

  • Map
  • NavigableMap
  • SortedMap
  • Cloneable
  • Serializable

Features of Java TreeMap

Some important features of TreeMap are:

  • Stores data as key-value pairs
  • Maintains keys in sorted order
  • Duplicate keys are not allowed
  • Duplicate values are allowed
  • Does not allow null keys
  • Allows multiple null values
  • Uses a Red-Black Tree internally
  • Supports custom sorting using Comparator
  • Dynamic size
  • Supports Generics

Syntax

Import Statement


import java.util.TreeMap;

or


import java.util.*;

Creating a TreeMap


TreeMap<Integer, String> students = new HashMap<>();

Using the Map interface:


Map<Integer, String> students = new HashMap<>();

Programming to the interface is considered a best practice.

Constructors of TreeMap

1. Default Constructor


TreeMap<Integer, String> students = new HashMap<>();

Creates an empty TreeMap that sorts keys in natural ascending order.

2. Constructor with Comparator


TreeMap<Integer, String> students = new HashMap<>(Collection.reavrseOrder());

Creates a TreeMap that sorts keys in descending order.

3. Constructor from Another Map


Map<Integer, String> map1 = new HashMap<>();

map1.put(101, "Rahul");
map1.put(103, "Neha");
map1.put(102, "Amit");

TreeMap<Integer, String> map2 =
        new TreeMap<>(map1);

System.out.println(map2);

Output

{101=Rahul, 102=Amit, 103=Neha}

Common Methods of TreeMap

Method Description
put() Adds or updates a key-value pair
get() Retrieves the value associated with a key
remove() Removes a key-value pair
containsKey() Checks whether a key exists
containsValue() Checks whether a value exists
firstKey() Returns the first key
lastKey() Returns the last key
higherKey() Returns the next higher key
lowerKey() Returns the next lower key

Example 1: Creating a TreeMap


import java.util.*;

public class TreeMapExample {

    public static void main(String[] args) {

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

        students.put(103, "Neha");
        students.put(101, "Rahul");
        students.put(102, "Amit");

        System.out.println(students);
    }
}

Output

{101=Rahul, 102=Amit, 103=Neha

Example 2: Updating a Value


import java.util.*;

public class UpdateExample {

    public static void main(String[] args) {

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

        students.put(101, "Rahul");

        students.put(101, "Rohan");

        System.out.println(students);
    }
}

Output

{101=Rohan}

The value is updated because duplicate keys are not allowed.

Example 3: Using firstKey() and lastKey()


import java.util.*;

public class FirstLastExample {

    public static void main(String[] args) {

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

        students.put(103, "Neha");
        students.put(101, "Rahul");
        students.put(102, "Amit");

        System.out.println(students.firstKey());
        System.out.println(students.lastKey());

    }
}

Output

101
103

Example 4: Iterating Through TreeMap


import java.util.*;

public class LoopExample {

    public static void main(String[] args) {

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

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        for (Map.Entry entry : students.entrySet()) {

            System.out.println(entry.getKey()
                    + " : "
                    + entry.getValue());
        }
    }
}

Output

101 : Rahul
102 : Amit
103 : Neha

Example 5: Descending Order


import java.util.*;

public class ReverseExample {

    public static void main(String[] args) {

        TreeMap<Integer, String> students =
        new TreeMap<>(Collections.reverseOrder());

        students.put(101, "Rahul");
        students.put(103, "Neha");
        students.put(102, "Amit");

        System.out.println(students);
    }
}

Output

{103=Neha, 102=Amit, 101=Rahul}

How TreeMap Works Internally

TreeMap internally uses a Red-Black Tree, which is a self-balancing binary search tree.

The process is:

  1. The key is compared with existing keys.
  2. The correct position is found.
  3. The entry is inserted into the tree.
  4. The tree automatically balances itself.
  5. Keys remain sorted at all times.

Because the tree remains balanced, operations such as insertion, deletion, and searching take O(log n) time.

Navigable Methods

TreeMap provides powerful navigation methods.


TreeMap<Integer, String> map= new HashMap<>();
map.put(10, "A");
map.put(20, "B");
map.put(30, "C");
map.put(40, "D");

System.out.println(map.higherKey(20));
System.out.println(map.lowerKey(20));
System.out.println(map.ceilingKey(25));
System.out.println(map.floorKey(25));

Output

30
10
30
20

These methods are useful for searching nearby keys.

TreeMap vs HashMap vs LinkedHashMap

Feature HashMap LinkedHashMap TreeMap
Duplicate Keys No No No
Duplicate Values Yes Yes Yes
Insertion Order No Yes No
Sorted Keys No No Yes
Null Key One One No
Null Values Yes Yes Yes
Internal Structure Hash Table Hash Table + Linked List Red-Black Tree
Performance Fastest Fast Slower

Time Complexity

Operation Time Complexity
put() O(log n)
get() O(log n)
remove() O(log n)
containsKey() O(log n)
firstKey() O(log n)
lastKey() O(log n)

Although slower than HashMap, TreeMap provides sorted keys automatically.

Real-life Example

Suppose you’re developing a student ranking system.

Marks:

Roll Number Marks
103 88
101 95
102 91

Using a TreeMap:


101=95
102=91
103=88

The records are automatically displayed in ascending order of roll numbers.

Other real-world applications include:

  • Phone directories
  • Product catalogs
  • Financial reports
  • Dictionary applications
  • Event scheduling
  • Leaderboards
  • Banking systems
  • Inventory management

Limitations of Java TreeMap

  • Slower than HashMap
  • Does not allow null keys
  • Uses more memory than HashMap
  • Not synchronized
  • Requires keys to be mutually comparable or a custom Comparator

Common Mistakes

1. Adding a Null Key


TreeMap<Integer, String> map =
        new TreeMap<>();
map.put(null, "Java");

This throws a NullPointerException.

2. Expecting Insertion Order


map.put(30, "C");
map.put(10, "A");
map.put(20, "B");

Output:

10=A
20=B
30=C

3. Forgetting Generics

Incorrect:


TreeMap map = new TreeMap();

Correct:


TreeMap<Integer, map =
        new TreeMap<>();

4. Using Non-Comparable Keys

If custom key objects do not implement Comparable and no Comparator is provided, a ClassCastException may occur.

5. Choosing TreeMap for Maximum Performance

If sorting is unnecessary, prefer HashMap because it offers faster average performance.

Best Practices

  • Declare variables using the Map interface.

 TreeMap<Integer, String> students =
        new TreeMap<>();
  • Use TreeMap only when sorted keys are required.
  • Use a custom Comparator for custom sorting logic.
  • Avoid null keys.
  • Use Generics for type safety.
  • Ensure custom key objects implement Comparable or provide a Comparator.

Conclusion

The Java TreeMap class is an excellent choice when your application requires sorted key-value pairs. Backed by a Red-Black Tree, it automatically keeps keys in ascending order while providing efficient insertion, deletion, searching, and advanced navigation operations.

Although TreeMap is slower than HashMap due to its sorting overhead, it is ideal for applications such as ranking systems, reports, catalogs, and scheduling tools where ordered data is essential.

Related Java Tutorials