How to reverse a TreeSet?

We know the TreeSet arranges the elements in increasing order.
This is because the default behavior of compare() in the TreeSet(Default comparator).
So if we use our custom comparator and override the compareTo() in our own choice then we can handle the sorting order.
Example:
import java.util.*;
class demo implements Comparator
{
public int compare(String s1,String s2){
return s2.compareTo(s1);
}
public static void main(String[] args){
TreeSet ts=new TreeSet(new demo());
ts.add("k");
ts.add("e");
ts.add("a");
ts.add("i");
ts.add("q");
ts.add("m");
ts.add("g");
System.out.println(ts);
}};

No comments:

Post a Comment