How to Create a TreeMap in Reverse Order in Java?


In this article, we will learn how to create a TreeMap in reverse order in java. Firstly, we need to know about TreeMap. A TreeMap in Java is a class that implements the SortedMap interface, which extends the Map interface. It is a collection that stores key-value pairs and organizes them based on their natural order or a custom Comparator provided during its creation.

This approach provides efficient performance for common operations such as adding, removing, and retrieving elements from the TreeMap. It has an average time complexity of O(log n), which ensures efficient execution.

Syntax for Creating a TreeMap

TreeMap(Map<? extends K,? extends V> m)  

This method is utilized to initialize a TreeMap by adding entries from 'm'. The entries will be sorted based on the natural order of the keys.

Approach

The default behaviour of a TreeMap is to sort its elements in ascending order based on the keys. However, by using the Collections.reverseOrder() method in Java, we can create a TreeMap that maintains the elements in reverse order, allowing us to display them in descending order based on the keys.

Collections.reverseOrder()

The reverseOrder() method returns a Comparator that can be used to sort a collection or list in reverse order based on a given Comparator. This method allows us to easily arrange elements in descending order using a custom comparator.

Syntax

public static  Comparator reverseOrder()

Input

tm.put("1", "Welcome");
tm.put("2", "to");
tm.put("3", "the");
tm.put("4", "Tutorials");
tm.put("5", "Point");

Output

// The goal is to print the elements in the reverse order of when they were inserted
5: Point
4: Tutorials
3: the
2: to
1: Welcome

Example

//The following code demonstrates how to iterate through a TreeMap in reverse order in Java.

import java.util.*;

public class Testing {
   public static void main(String args[]){
      //Creating a tree Map
      Map<String, String> tm =
      new TreeMap<String, String>(Collections.reverseOrder());

      // Use put() method to insert elements into a treemap
      tm.put("1", "Welcome");
      tm.put("2", "to");
      tm.put("3", "the");
      tm.put("4", "Tutorials");
      tm.put("5", "Point");

      // Traversing and printing the elements in map
      for(Map.Entry<String,String> me: tm.entrySet()){
         System.out.println(me.getKey() + " : " + me.getValue());
      }
   }
}

Output

5 : Point
4 : Tutorials
3 : the
2 : to
1 : Welcome

The elements in the example are being displayed in the reverse order based on their keys.

In this example we are creating a class named Person where it consists of  two attributes like name and age. Here we are going to create a TreeMap with a key as Integer and value will be the Person Object and display them in Reverse Order.

Input

treeMap.put(1, new Person("Hari", 25));
treeMap.put(2, new Person("Revanth", 30));
treeMap.put(3, new Person("Mohan", 35));
t  

Output

David (40 years old) => Key: 4
Charlie (35 years old) => Key: 3
Bob (30 years old) => Key: 2
Alice (25 years old) => Key: 1  

Below Program helps us to traverse a TreeMap in reverse order for the above example −

Example

//The code snippet below illustrates how to traverse a TreeMap in reverse order using Java.
import java.util.*;

class PersonDetails {
   private String person_name;
   private int person_age;

   public PersonDetails(String name, int age) {
      this.person_name = name;
      this.person_age = age;
   }

   public String getName() {
      return person_name;
   }

   public int getAge() {
      return person_age;
   }

   @Override
   public String toString() {
      return person_name + " (" + person_age + " years old)";
   }
}

public class Testing {
   public static void main(String[] args) {
      // Create a TreeMap with Integer as Key and value as Person(Name,age)
      TreeMap<Integer, PersonDetails> tm = new TreeMap<>(Collections.reverseOrder());

      // Use put() method to insert elements into a treemap

      tm.put(1, new PersonDetails("Alice", 25));
      tm.put(2, new PersonDetails("Bob", 30));
      tm.put(3, new PersonDetails("Charlie", 35));
      tm.put(4, new PersonDetails("David", 40));

      // Traversing and printing the elements in map
      for (Map.Entry<Integer, PersonDetails> me : tm.entrySet()) {
         System.out.println(me.getValue() + " => Key: " + me.getKey());
      }
   }
}

Output

David (40 years old) => Key: 4
Charlie (35 years old) => Key: 3
Bob (30 years old) => Key: 2
Alice (25 years old) => Key: 1

In this example we are creating a class named Product where it consists of  two attributes like name and price. Here we are going to create a TreeMap with key as product_name and value as product_price and display them in Reverse Order.

Input

tm.put("Product A", 9.99);
tm.put("Product B", 5.99);
tm.put("Product C", 12.49);
tm.put("Product D", 7.99);
tm.put("Product E", 3.99);

Output

Product E => $3.99
Product D => $7.99
Product C => $12.49
Product B => $5.99
Product A => $9.99

Example

//The code snippet below illustrates how to traverse a TreeMap in reverse order using Java.

import java.util.*;

class ProductDetails {
   private String product_name;
   private double product_price;

   public ProductDetails(String name, double price) {
      this.product_name = name;
      this.product_price = price;
   }

   public String getName() {
      return product_name;
   }

   public double getPrice() {
      return product_price;
   }

   @Override
   public String toString() {
      return product_name + " ($" + product_price + ")";
   }
}

public class Testing {
   public static void main(String[] args) {
      // Create a TreeMap with key as product_name and value as product_price
      TreeMap<String, Double> tm= new TreeMap<>(Collections.reverseOrder());

      // Use put() method to insert elements into a treemap
      tm.put("Product A", 9.99);
      tm.put("Product B", 5.99);
      tm.put("Product C", 12.49);
      tm.put("Product D", 7.99);
      tm.put("Product E", 3.99);

      // Print the TreeMap
      for (Map.Entry<String, Double> me : tm.entrySet()) {
         System.out.println(me.getKey() + " => $" + me.getValue());
      }
   }
}

Output

Product E => $3.99
Product D => $7.99
Product C => $12.49
Product B => $5.99
Product A => $9.99

Conclusion

In this article, we have explored the process of creating a TreeMap in reverse order by utilizing the reverseOrder() method and we have seen a few examples how to use this reverseOder() method in performing this task.

Updated on: 16-Oct-2023

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements