How to Create TreeMap Objects using Comparable Interface in Java?


TreeMap is a class of Java Collection Framework that implements NavigableMap Interface. It stores the elements of the map in a tree structure and provides an efficient alternative to store the key-value pairs in sorted order. Note that while creating objects of TreeMap we need to use the comparable interface so that we can maintain the sorting order of its elements. In this article, we are going to discuss a few Java programs to create TreeMap objects using comparable interface.

Java Program to create TreeMap Objects using Comparable Interface

Before jumping to the Java program directly, let's have a brief look at the basics of Comparable Interface.

Comparable Interface

This interface is useful when we want to sort custom objects by their natural ordering. For example, It sorts strings in dictionary order and numerics in numerical order. This interface is available in 'java.lang' package. Generally, classes and interfaces defined in this package are by default available for our use therefore, it is not necessary to import this package explicitly.

Syntax

class nameOfclass implements Comparable

Here, class is the keyword that creates a Class and implements is the keyword that enables the use of features provided by an Interface.

compareTo()

The Comparable interface defines only a single method named 'CompareTo' that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. It returns 0 when 'this' object is equal to the passed object, a positive value if 'this' object is greater otherwise a negative value.

Syntax

compareTo(nameOfclass nameOfobject); 

Since a TreeMap stores its element in the form of the key-value pairs in sorted order, therefore, we need to use the Comparable Interface otherwise we will encounter a ClassCastException.

Example

The following example illustrates the use of Comparable Interface in creating TreeMap.

Approach

  • Create a class 'TrMap' that implements Comparable Interface. Inside it, declare two variables and define a constructor of this class along with two parameters 'item' and 'price' of type string and double respectively.

  • Moving further we will convert the data of object into string using 'toString()' method. Then, define 'compareTo' method along with an object of class 'TrMap' as a parameter to compare 'this' object with the newly created object.

  • Now, in the main() method, declare an object named 'obj' of class 'TrMap' of TreeMap and using an inbuilt method named 'put()' store the details of object to it. The 'item' is key and its corresponding value is 'price'.

  • In the end, use the 'keySet()' method inside a for-each loop to retrieve and print the values associated with keys.

Example

import java.util.*;
import java.lang.*;
public class TrMap implements Comparable<TrMap> {
   String item;
   int price;
   TrMap(String item, int price) {
   // this keyword shows these variables belong to constructor
      this.item = item; 
      this.price = price;
   }
   // method for converting object into string
   public String toString() {
      return "Item: " + item + ", " + "Price: " + price;
   }
   public String getName() {
      return this.item;
   }
   // overriding method
   public int compareTo(TrMap comp) {
      return this.item.compareTo(comp.item);
   }
   public static void main(String[] args) {
      // Declaring collection TreeMap
      TreeMap<String, TrMap> obj = new TreeMap<>();
      // Adding object to the obj map
      TrMap obj1 = new TrMap("TShirt", 495);
      obj.put(obj1.getName(), obj1);
      TrMap obj2 = new TrMap("Shirt", 660);
      obj.put(obj2.getName(), obj2);
      TrMap obj3 = new TrMap("Kurti", 455);
      obj.put(obj3.getName(), obj3);
       // printing details obj map
      System.out.println("Elements of the map: ");
      for (String unKey : obj.keySet()) {
         System.out.println(obj.get(unKey));
      }
   }
}

Output

Elements of the map: 
Item: Kurti, Price: 455
Item: Shirt, Price: 660
Item: TShirt, Price: 495

In the above output, the elements are sorted based on the Item name.

Conclusion

We started this article by defining the TreeMap class of Java Collection Framework and in later sections, we introduced the Comparable Interface and its in-built method named compareTo. In the end, we discussed a Java program to get a better understanding of the use of Comparable Interface in creating TreeMap.

Updated on: 19-Jul-2023

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements