How to Change the Comparator to Return a Descending Order in Java TreeSet? - GeeksforGeeks

17 Jan, 2022
Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. TreeSet is one of the most important implementations 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. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. 
Syntax: For the comparator is as follows:
public int compare(Object obj1, Object obj2):
Methods: Getting descending order in TreeSet by changing the comparator.
With user-defined classWithout user-defined class
With user-defined class
Without user-defined class
Method 1: With user-defined class
To change the comparator, a user-defined class is created that implements the Comparator interface more specifically descendingComparator for which pseudo code is as followed for clear understanding before implementing the same. descendingComparator() is passed as an argument in the TreeSet at the inst stance of creation to get the corresponding descending Order set.
Syntax: Passing descendingComparator()
Pseudo Code: TreeSet<String> set = new TreeSet<>(new descendingComparator());
Pseudo Code: Approach
class descendingComparator implements Comparator<String> {

public int compare(String i1, String i2) {

    // compare using compareTo() method
    return i2.compareTo(i1);
  }
}
Example
Java
// Java Program to Change the Comparator to Return a// Descending Order in Java TreeSet // Importing all classes of// java.util packageimport java.util.*; // User0defined class (Helper class)// New class that implements comparator interfaceclass descendingComparator implements Comparator<Integer> {     public int compare(Integer i1, Integer i2)    {        // compare using compareTo() method        return i2.compareTo(i1);    }} // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {         // Create a TreeSet and pass descendingComparator()        // as made in another class as parameter        // to it to get Descending Order        TreeSet<Integer> set            = new TreeSet<>(new descendingComparator());         // Adding elements to Treeset        // Custom inputs        set.add(10);        set.add(20);        set.add(30);         // Print Descending Ordered set in descending order        // as above descendComparator() usage        System.out.println("Descending Ordered set : "                           + set);    }}
Method 2: Without user-defined class
Comparator to return a descending order in Java TreeSet at the time of the creation of TreeSet instead of making a new class.
Pseudo Code: Approach

TreeSet<Integer> set = new TreeSet<Integer>(new Comparator<Integer>()
{
    public int compare(Integer i1,Integer i2)
     {
          // comparing using compareTo() method
          return i2.compareTo(i1);
     }
 });
Example
Java
// Java Program to Change the Comparator// to Return Descending Order in Java TreeSet // Importing all classes of// java.util packageimport java.util.*; // Main classpublic class GFG {     // Main driver method    public static void main(String[] args)    {        // implements comparator interface        // to get Descending Order         // Method 2: At the time of creation of TreeSet         // Creating(defining) a TreeSet        TreeSet<Integer> set = new TreeSet<Integer>(            new Comparator<Integer>() {                               // Changing the comparator                public int compare(Integer i1, Integer i2)                {                    return i2.compareTo(i1);                }            });         // Add elements to above created TreeSet        // Custom inputs        set.add(10);        set.add(20);        set.add(30);         // Print Descending Ordered TreeSet        System.out.println("Descending Ordered Treeset : "                           + set);    }}
Descending Ordered set : [30, 20, 10]
 
ruhelaa48
saurabh1990aror
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?