Java TreeMap Class


The TreeMap class belongs to the Java Collections Framework and resides in the java.util package. The TreeMap structure maintains key-value pairs in ascending order through a Red-Black Tree and implements both NavigableMap and SortedMap interfaces.


Key Features

  • Stores key-value pairs, just like HashMap
  • This collection orders keys based on their natural sequence or through a custom comparator function.
  • The TreeMap does not permit null keys but allows multiple null values.
  • The storage structure of TreeMap uses a Red-Black Tree which keeps balance as a binary search tree.
  • Not synchronized (thread-unsafe)

Syntax

TreeMap<KeyType, ValueType> map = new TreeMap<>(); 

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

Example

import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<Integer, String> employeeMap = new TreeMap<>();

        // Adding entries
        employeeMap.put(3, "Charlie");
        employeeMap.put(1, "Alice");
        employeeMap.put(2, "Bob");

        // Sorted by key
        System.out.println("Employee Map: " + employeeMap);

        // First and last
        System.out.println("First Key: " + employeeMap.firstKey());
        System.out.println("Last Entry: " + employeeMap.lastEntry());

        // Iterating over map
        for (Map.Entry<Integer, String> entry : employeeMap.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
        }

        // Submap example
        System.out.println("Head Map (keys < 3): " + employeeMap.headMap(3));
    }
}
 

Note

  • Either the keys must implement the Comparable interface or a Comparator needs to be supplied.
  • Inserting null keys is prohibited because they result in a NullPointerException.
  • This data structure serves best when you require access to sorted keys along with high-performance range queries.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.