Back to Java
2025-12-256 min read

Java TreeMap

Learn Java TreeMap step by step with clear examples and exercises.

Title: Java TreeMap - A full guide for Efficient Data Management

Why This Matters

In programming, managing data efficiently is crucial. Java's TreeMap provides an effective solution for maintaining sorted associative arrays (maps) of keys and values. This data structure is particularly useful in situations where you need to maintain the elements in a specific order or perform operations such as range searches, floor, and ceiling operations. Understanding TreeMap can help you tackle real-world programming challenges more effectively and even ace coding interviews.

Prerequisites

Before diving into Java TreeMap, make sure you have a solid understanding of the following concepts:

  1. Basic Java syntax (variables, methods, classes, etc.)
  2. Interfaces and abstract classes
  3. Comparable interface and its implementation
  4. Map interface and common map implementations like HashMap and LinkedHashMap
  5. Concepts of binary search trees and their advantages for sorted data structures
  6. Understanding the difference between ascending and descending order

Core Concept

Creating a TreeMap

To create a TreeMap in Java, use the following syntax:

import treeMapPackage; // e.g., import java.util.TreeMap;

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

Replace treeMapName, KeyType, and ValueType with your desired names and data types for the map. By default, a TreeMap is sorted according to its natural ordering (ascending order). You can customize this behavior by providing a Comparator object while creating the TreeMap or by implementing the Comparable interface in your key class.

Basic Operations

  1. Adding elements: Use the put() method to add a new key-value pair:
treeMapName.put(key, value);
  1. Retrieving values: Access a value using its corresponding key with the get() method:
ValueType value = treeMapName.get(key);
  1. Checking for presence: Use the containsKey() method to check if a specific key exists in the TreeMap:
boolean isPresent = treeMapName.containsKey(key);
  1. Removing elements: To remove a key-value pair, use the remove() method:
treeMapName.remove(key);
  1. Size and emptiness: Get the number of elements in the TreeMap with the size() method or check if it's empty using the isEmpty() method.
int size = treeMapName.size();
boolean isEmpty = treeMapName.isEmpty();

Navigating the TreeMap

  1. First and last elements: Get the first (lowest) and last (highest) keys using the firstKey() and lastKey() methods, respectively:
KeyType first = treeMapName.firstKey();
KeyType last = treeMapName.lastKey();
  1. Floor and ceiling: Get the greatest key less than or equal to a given key using the floorKey() method, and the least key greater than or equal to a given key using the ceilingKey() method:
KeyType floor = treeMapName.floorKey(key);
KeyType ceiling = treeMapName.ceilingKey(key);
  1. Higher and lower: Get the successor (higher) and predecessor (lower) of a given key using the higherKey() and lowerKey() methods, respectively:
KeyType higher = treeMapName.higherKey(key);
KeyType lower = treeMapName.lowerKey(key);
  1. Submap: Create a submap containing all key-value pairs whose keys are between (and including) two given keys using the subMap() method:
TreeMap<KeyType, ValueType> subMap = treeMapName.subMap(fromKey, toKey);
  1. Head and tail maps: Create a view of the portion of the map whose keys are less than (headMap) or greater than (tailMap) a given key using the headMap() and tailMap() methods:
TreeMap<KeyType, ValueType> headMap = treeMapName.headMap(key);
TreeMap<KeyType, ValueType> tailMap = treeMapName.tailMap(key);

Worked Example

Let's create a TreeMap to store student records, where keys are student IDs and values are Student objects (containing name, age, and GPA).

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

class Student implements Comparable<Student> {
String name;
int age;
double gpa;

// Constructor, getters, setters, and toString() methods go here...

@Override
public int compareTo(Student other) {
return Double.compare(this.gpa, other.gpa); // Sort students by GPA (descending order)
}
}

public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, Student> studentTreeMap = new TreeMap<>(Comparator.reverseOrder());

Student s1 = new Student("Alice", 20, 3.8);
Student s2 = new Student("Bob", 22, 3.9);
Student s3 = new Student("Charlie", 21, 3.7);

studentTreeMap.put(s1.getId(), s1);
studentTreeMap.put(s2.getId(), s2);
studentTreeMap.put(s3.getId(), s3);

// Access values using get() method and iterate through the TreeMap
for (Student student : studentTreeMap.values()) {
System.out.println(student);
}

// Print the first and last students
System.out.println("First student: " + studentTreeMap.firstKey());
System.out.println("Last student: " + studentTreeMap.lastKey());
}
}

Common Mistakes

  1. Forgetting to import the TreeMap package: Always make sure you have imported the necessary package at the beginning of your code.
  2. Not implementing Comparable interface for custom sorting: If you want to sort keys based on a custom order, implement the Comparable interface in the key class and override its compareTo() method accordingly.
  3. Using incompatible data types for keys or values: Ensure that the data types used for keys and values are compatible with TreeMap's generic type declarations.
  4. Removing elements without checking for presence: Always check if a key exists before removing it to avoid NullPointerException.
  5. Not considering null values: By default, TreeMap does not allow null keys or duplicate keys. If you need to store null values or duplicate keys, use HashMap instead.
  6. Creating a TreeMap with an inappropriate Comparator: Make sure your comparator correctly implements the compare() method and is consistent with the natural ordering of the keys.

Practice Questions

  1. Create a TreeMap of strings sorted in descending order using a custom Comparator.
  2. Implement a method that returns the minimum value (lowest GPA) from a given TreeMap of Student objects.
  3. Write a program that finds all students with a GPA less than or equal to 3.5 and prints their names.
  4. Create a TreeMap where keys are integers, values are strings, and the map is sorted in ascending order by the length of the string value.
  5. Implement a method that merges two TreeMaps, combining their key-value pairs into one TreeMap.
  6. Write a program that prints all students whose names start with a specific letter (e.g., 'A').
  7. Create a TreeMap where keys are custom objects representing employees, values are their salaries, and the map is sorted by employee's last name in ascending order.

FAQ

  1. Can I use null keys in a TreeMap? No, TreeMap does not allow null keys. If you need to store null values, use HashMap instead.
  2. What is the time complexity of basic operations in a TreeMap? The average time complexity for basic operations (insertion, deletion, search) in a balanced binary search tree like TreeMap is O(log n).
  3. Can I create a TreeMap with a custom key-value pair data structure as its values? Yes, you can use any object that implements the Map.Entry interface as a value in a TreeMap.
  4. What happens when I try to add duplicate keys to a TreeMap? If you attempt to add duplicate keys to a TreeMap, the last key-value pair added will overwrite the previous one with the same key.
  5. Is it possible to create a TreeMap that maintains keys in descending order by default? Yes, you can specify a custom comparator while creating the TreeMap to sort keys in descending order by default.
  6. Can I use a TreeMap as a key in another Map or Collection? No, you cannot directly use a TreeMap as a key in another map or collection due to its implementation as a navigable map. However, you can convert it to a List (using the keySet() method) and then use that List as a key.
  7. What is the difference between TreeMap and HashMap? Both TreeMap and HashMap are implementations of the Map interface in Java, but they differ in their sorting behavior: TreeMap maintains its keys in sorted order, while HashMap does not. Additionally, TreeMap provides additional methods for navigating the map based on key ranges and specific keys.
Java TreeMap | Java | XQA Learn