How to Create TreeMap Objects using Comparable Interface in Java?
Last Updated :
22 Feb, 2023
In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Comparable interface to define the natural ordering of the keys.
Here's an example of how to create a TreeMap object using the Comparable interface in Java:
Java
import java.util.*;
class Person implements Comparable<Person> {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
// Implement the compareTo() method of the Comparable interface
@Override
public int compareTo(Person other) {
return Integer.compare(this.id, other.getId());
}
}
public class Example {
public static void main(String[] args) {
// Create a TreeMap object using the Person class that implements Comparable interface
TreeMap<Person, String> treeMap = new TreeMap<>();
// Add some key-value pairs to the TreeMap
treeMap.put(new Person(2, "John"), "value1");
treeMap.put(new Person(1, "Alice"), "value2");
treeMap.put(new Person(3, "Bob"), "value3");
// Iterate over the TreeMap and print the key-value pairs
for (Map.Entry<Person, String> entry : treeMap.entrySet()) {
Person key = entry.getKey();
String value = entry.getValue();
System.out.println(key.getId() + " " + key.getName() + " " + value);
}
}
}
Output1 Alice value2
2 John value1
3 Bob value3
In this example, we have created a Person class that implements the Comparable interface and overrides the compareTo() method to define the natural ordering of the objects based on the id field. Then, we have created a TreeMap object using the Person class as the key and a String as the value. We have added some key-value pairs to the TreeMap and iterated over the entries to print the key-value pairs in sorted order based on the id field.
Note that if the keys are not unique, the TreeMap will only store the last value associated with the key. If you want to store multiple values for a key, you can use a Map implementation that supports multiple values per key, such as a HashMap with a List as the value.
Comparable interface is found in java.lang package which is used to order the objects of a user-defined class on the basis of a single attribute only. This interface contains a single method compareTo(Object). It is used to compare the current object with the specified objects and can be used o sort user-defined classes, wrapper class, and string objects.
Syntax:
compareTo(Object o) ;
Parameter: The specified object with which the current object is being compared.
Return Type: Integer value
- Positive integer — If the current object is greater than the specified object.
- Negative integer — If the current object is lesser than the specified object.
- Zero — If the current object is equal to the specified object.
Use of Comparable Interface in Java
TreeMap in Java, elements are stored as key-value pairs which are sorted on the basis of the key. When the Key is of String class or Wrapper Classes, it implements the Comparable interface by default and stores the elements in sorted order. However, if somebody wants to make the desired key of a particular user-defined type i.e user-defined class, we need to implement the Comparable interface to order the objects in a particular order on the basis of an attribute.
Implementation: Without using the comparable interface.
Java
// Creating TreeMap objects using
// Comparable interface in Java
// Importing all generic java utility and input
import java.io.*;
import java.util.*;
// Class - User defined named Employee
public class Employee {
// Attributes of object of class
int id;
String name;
// Parameterized constructor for user-defined class
public Employee(int id, String name)
{
// This keyword refers to current object in a
// constructor
this.id = id;
this.name = name;
}
}
// Main class
class GFG {
// Main driver method
public static void main(String[] args) throws Exception
{
// Declaring and initializing a TreeMap
TreeMap<Employee, String> tm = new TreeMap<>();
// Employee object1
// custom input
Employee e1 = new Employee(1, "Pathak");
// Employee object2
// custom input
Employee e2 = new Employee(2, "Anshu");
// Put method associating specific key-value in Map
tm.put(e1, "First");
tm.put(e2, "Second");
// Iterating over Map using for-each loop
// Map with employee Key
for (Map.Entry<Employee, String> e :
tm.entrySet()) {
// Print key-value pairs of TreeMap
System.out.println(e.getKey().id + " "
+ e.getValue());
}
}
}
Output: Error

The above code throws exceptions as the comparable interface has not been implemented and hence it cannot order the map elements on the basis of a key in proper order. So, in order to handle the exception
Implementation: With using the comparable interface.
Java
// Creating TreeMap objects using
// Comparable interface in Java
// Importing all generic java utility and input
import java.io.*;
import java.util.*;
// User-defined class named Employee
// implementing comparable
public class Employee implements Comparable<Employee> {
// Attributes of object of class
int id;
String name;
// Parameterized constructor for user-defined class
public Employee(int id, String name)
{
// This keyword refers to
// current object in a constructor
this.id = id;
this.name = name;
}
// Comparable interface
public int compareTo(Employee e)
{
// Two instance of class can be compared
int diff = this.id - e.id;
// Note: Two equal employee Id will return 0
return diff;
}
}
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring and initializing a TreeMap
TreeMap<Employee, String> tm = new TreeMap<>();
// Employee object1 (custom input)
Employee e1 = new Employee(1, "Pathak");
// Employee object2 (custom input)
Employee e2 = new Employee(2, "Anshu");
// Put method associating specific key-value in Map
tm.put(e1, "First");
tm.put(e2, "Second");
// Iterating over Map using for-each loop
// Map with employee key
for (Map.Entry<Employee, String> e :
tm.entrySet()) {
// Print key-value pairs of TreeMap
System.out.println(e.getKey().id + " "
+ e.getKey().name + " "
+ e.getValue());
}
}
}
Output1 Pathak First
2 Anshu Second
Similar Reads
How to Sort TreeSet Elements using Comparable Interface in Java?
TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a Set using their natural ordering whether an explicit comparator is provided. To sort TreeSet elements using Comparable interface in java first, we create a cl
3 min read
How to Sort HashSet Elements using Comparable Interface in Java?
The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means when we iterate the HashSet, there is no guarantee that we get elements in which order they were inserted. To sort HashSe
3 min read
How to Sort Vector Elements using Comparable Interface in Java?
Vector is a child interface of collection. If we want to represent a group of the individual objects as a single entity where duplicates are allowed and insertion order must be preserved then we should go for vector. It is a resizable or growable array. It implements a Serializable, Cloneable, and R
5 min read
How to Compare Two TreeMap Objects in Java?
TreeMap class in java provides a way of storing key-value pairs in sorted order. The below example shows how to compare two TreeMap objects using the equals() method. It compares two TreeMap objects and returns true if both of the maps have the same mappings else returns false. Syntax: boolean equal
1 min read
How to Sort LinkedHashSet Elements using Comparable Interface in Java?
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
3 min read
Sort LinkedHashMap by Keys using Comparable Interface in Java
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. To sort LinkedHashMap by key
3 min read
How to Create a TreeMap in Java and Add Key-Value Pairs in it?
In Java, a TreeMap maintains elements in a sorted order as it is an implementation of the SortedMap Interface. It stores key-value pairs in a sorted order. In this article, we will explore the creation of TreeMap in Java and learn the step-by-step process of adding key-value pairs. Program to Create
2 min read
How to Avoid Duplicate User Defined Objects in TreeSet in Java?
TreeSet class in Java is part of Javaâs collections framework which implements the NavigableSet interface, which provides functionalities to navigate through the SortedSet. The NavigableSet further extends the SortedSet interface, which provides functionalities to keep the elements sorted. As the Tr
5 min read
Creating TreeSet with Comparator by User Define Objects in Java
TreeSet is the implementation class of Set Interface. It follows a natural sorting order or you can customize it using a comparator and it also does not allow duplicates. Syntax: TreeSet<String> gfg= new TreeSet<>(); Below is the normal implementation of the TreeSet: Java // Java program
6 min read
How to Implement a Cache Eviction Policy using TreeMap in Java?
To enhance application speed, caching is a method that stores frequently visited data in memory. When the cache fills up, a cache eviction policy decides which things must be removed. A sorted map implementation is provided by Java's TreeMap, which may be used to create a cache with a unique evictio
3 min read