Yes, custom objects can be used as keys in a TreeMap. However, unlike HashMap, TreeMap must be able to compare and sort its keys. Therefore, the key class must either implement the Comparable interface or a Comparator must be provided while creating the TreeMap. Otherwise, a ClassCastException will occur at runtime.
Why Does TreeMap Need Comparable or Comparator?
TreeMap is internally implemented using a Red-Black Tree.
Without comparison logic, TreeMap cannot maintain sorted order.
Using Comparable
The key class can implement Comparable.
class Employee implements Comparable<Employee> {
private int id;
public Employee(int id) {
this.id = id;
}
@Override
public int compareTo(Employee other) {
return Integer.compare(
this.id,
other.id);
}
}Now Employee objects can be used directly as TreeMap keys.
Using Comparator
If modifying the class is not possible, a Comparator can be supplied.
TreeMap<Employee, String> map =
new TreeMap<>(
Comparator.comparing(
Employee::getId));This allows custom sorting logic without changing the class.
Suppose we want employee records sorted by employee ID.
103 → Mike
101 → John
102 → David
101 → John
102 → David
103 → Mike
import java.util.TreeMap;
class Employee
implements Comparable<Employee> {
private int id;
Employee(int id) {
this.id = id;
}
@Override
public int compareTo(Employee other) {
return Integer.compare(
this.id,
other.id);
}
@Override
public String toString() {
return String.valueOf(id);
}
}
public class Demo {
public static void main(String[] args) {
TreeMap<Employee, String> map =
new TreeMap<>();
map.put(new Employee(103), "Mike");
map.put(new Employee(101), "John");
map.put(new Employee(102), "David");
System.out.println(map);
}
}{101=John, 102=David, 103=Mike}
What Happens If Comparable or Comparator Is Missing?
class Employee {
private int id;
Employee(int id) {
this.id = id;
}
}
TreeMap<Employee, String> map =
new TreeMap<>();
map.put(new Employee(101), "John");ClassCastException
TreeMap does not know how to compare Employee objects.
TreeMap vs HashMap for Custom Objects
Real-World Use Cases
A concise interview answer is
Yes, custom objects can be used as keys in a TreeMap, provided the objects can be compared. This is typically achieved by implementing the Comparable interface or supplying a Comparator. Since TreeMap maintains keys in sorted order using a Red-Black Tree, it must be able to compare keys to determine their position in the tree.
Last updated: 11 November 2026
Previous question: When would you use a TreeMap instead of a HashMap?
Next question: What are the SOLID principles?