Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

TreeMap

TreeMap is a class available in the java.util package. It extends the java.util.AbstractMap class and implements the java.util.NavigableMap, java.lang.Cloneable, and java.io.Serializable interfaces.

Important points of java.util.TreeMap:

1. We can store the elements in TreeMap in a key-value format.
2. Key objects must be of the same type, and we can store different types of values.
3. Null values are not allowed as keys or values.
4. It stores the data in sorted order based on the defined natural sorting order or a specified comparator.
5. None of the methods of java.util.TreeMap are synchronized.
6. Because java.util.TreeMap implements java.lang.Cloneable and java.io.Serializable interfaces, it is eligible for cloning and serialization.
7. Internally, TreeMap uses a Red-Black Tree Data Structure, which is a self-balancing Binary Search Tree, to map its elements.

Important Constructor of java.util.TreeMap:

1. public java.util.TreeMap(): It creates an empty TreeMap that stores elements based on the Key object and employs natural sorting. All classes used as Key objects must implement the java.lang.Comparable interface, and the implementation of the compareTo() method should not throw ClassCastException for any key.

            
importjava.util.TreeMap;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      TreeMapmap = newTreeMap();
      map.put(1, "V-1");
      map.put(2, "V-2");
      map.put(3, "V-3");
      map.put(4, "V-4");
      map.put(5, "V-5");
      System.out.println("map :- " + map);
   }
}
    map :- {1=V-1, 2=V-2, 3=V-3, 4=V-4, 5=V-5}
            

In this example, we are using objects of the java.lang.Integer type. The Integer class implements the java.lang.Comparable interface, and its defined natural sorting order is ascending order.

            
importjava.util.TreeMap;
class Student implementsComparable {
   String sname;
   intmarks;
   public Student(String sname, intmarks) {
      super();
      this.sname = sname;
      this.marks = marks;
   }
   @Override
   public String toString() {
      return "Student [sname=" + sname + ", marks=" + marks + "]";
   }
   // Defining default Natural Sorting Order [Descending Order] for Student class.
   publicintcompareTo(Object o) {
      Student s = (Student) o;
      if (this.marks > s.marks) {
         return -1;
      }
      elseif(this.marks == s.marks) {
         return 0;
      } else {
         return 1;
      }
   }
}
publicclass JTC {
   publicstaticvoid main(String[] args) {
      TreeMapmap = newTreeMap();
      map.put(new Student("Vivek", 89), "V-1");
      map.put(new Student("Amit", 123), "V-2");
      map.put(new Student("Rahul", 93), "V-3");
      map.put(new Student("Nandan", 103), "V-4");
      map.put(new Student("Neha", 789), "V-5");
      System.out.println("map :- " + map);
   }
}
    map :- {Student [sname=Neha, marks=789]=V-5, Student [sname=Amit, marks=123]=V-2, Student [sname=Nandan, marks=103]=V-4, Student [sname=Rahul, marks=93]=V-3, Student [sname=Vivek, marks=89]=V-1}
            

In this example, we are establishing the natural sorting order for the Student class by implementing the java.lang.Comparable interface and overriding the compareTo() method. The natural sorting order for Student class objects is set to descending order based on the student's marks.

2. public java.util.TreeMap(java.util.Comparator): It creates an empty TreeMap and stores data in sorted order according to the specified Comparator. The compare() method of the java.util.Comparator interface must not throw a ClassCastException. If the specified Comparator is null, TreeMap will sort based on the given Natural Sorting Order.

            
importjava.util.Comparator;
importjava.util.TreeMap;
class Student implementsComparable {
   String sname;
   intmarks;
   public Student(String sname, intmarks) {
      super();
      this.sname = sname;
      this.marks = marks;
   }
   @Override
   public String toString() {
      return "Student [sname=" + sname + ", marks=" + marks + "]";
   }
   // Defining default Natural Sorting Order [Descending Order] for Student class.
   publicintcompareTo(Object o) {
      Student s = (Student) o;
      if (this.marks > s.marks) {
         return -1;
      }
      elseif(this.marks == s.marks) {
         return 0;
      } else {
         return 1;
      }
   }
}
classStudentMarksComparatorimplementsComparator {
   // Defining Comparator [Ascending Order] which compares on the basis of Student marks.
   publicint compare(Object o1, Object o2) {
      Student s1 = (Student) o1;
      Student s2 = (Student) o2;
      if (s1.marks > s2.marks) {
         return 1;
      }
      elseif(s1.marks == s2.marks) {
         return 0;
      } else {
         return -1;
      }
   }
}
publicclass JTC {
   publicstaticvoid main(String[] args) {
      // TreeMap working on StudentMarksComparator
      TreeMapmap = newTreeMap(newStudentMarksComparator());
      map.put(new Student("Vivek", 89), "V-1");
      map.put(new Student("Amit", 123), "V-2");
      map.put(new Student("Rahul", 93), "V-3");
      map.put(new Student("Nandan", 103), "V-4");
      map.put(new Student("Neha", 789), "V-5");
      System.out.println("map :- " + map);
      // Because Specified Comparator is null so HashMap will sort using Natural Sorting. 
      TreeMapmap1 = newTreeMap((StudentMarksComparator) null);
      map1.put(new Student("Vivek", 89), "V-1");
      map1.put(new Student("Amit", 123), "V-2");
      map1.put(new Student("Rahul", 93), "V-3");
      map1.put(new Student("Nandan", 103), "V-4");
      map1.put(new Student("Neha", 789), "V-5");
      System.out.println("map1 :- " + map1);
   }
}
    map :- {Student [sname=Vivek, marks=89]=V-1, Student [sname=Rahul, marks=93]=V-3, Student [sname=Nandan, marks=103]=V-4, Student [sname=Amit, marks=123]=V-2, Student [sname=Neha, marks=789]=V-5}
    map1 :- {Student [sname=Neha, marks=789]=V-5, Student [sname=Amit, marks=123]=V-2, Student [sname=Nandan, marks=103]=V-4, Student [sname=Rahul, marks=93]=V-3, Student [sname=Vivek, marks=89]=V-1}
            

In this example, we are defining a custom Comparator (StudentMarksComparator) that compares two students based on their marks. The first TreeMap uses this specified Comparator.
In the second TreeMap (map1), the specified Comparator is null, so this TreeMap sorts its mappings using the defined Natural Sorting Order.

3. public java.util.TreeMap(java.util.Map): It creates a TreeMap that contains all the mappings of the specified Map. The order will be the same as in the specified Map. Key objects must be of the Comparable type; otherwise, a ClassCastException is thrown. If the specified Map is null, a NullPointerException is thrown.