How to Change the Comparator to Return a Descending Order in Java TreeSet?
Last Updated :
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 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
import java.util.*;
class descendingComparator implements Comparator<Integer> {
public int compare(Integer i1, Integer i2)
{
return i2.compareTo(i1);
}
}
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> set
= new TreeSet<>( new descendingComparator());
set.add( 10 );
set.add( 20 );
set.add( 30 );
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
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> set = new TreeSet<Integer>(
new Comparator<Integer>() {
public int compare(Integer i1, Integer i2)
{
return i2.compareTo(i1);
}
});
set.add( 10 );
set.add( 20 );
set.add( 30 );
System.out.println( "Descending Ordered Treeset : "
+ set);
}
}
|
Output
Descending Ordered set : [30, 20, 10]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...