I am creating a simple program to learn about the Java Comparator class. I have sorted an Arraylist
into order but now I want to sort the list in descending order b
One way to implement an reverse order comparator is to implement an Compartor-Delegate that invert the comparator result (by changing the order).
public class ReverseOrder implements Comparator {
private Comparator delegate;
public ReverseOrder(Comparator delegate){
this.delegate = delegate;
}
public int compare(T a, T b) {
//reverse order of a and b!!!
return this.delegate.compare(b,a);
}
}
So the only thing you need to do is to use this delegate. For example:
Comparator myComparator = new myComparator();
List list = ...;
List reverse = new ArrayList(list);
//acceding
Collections.sort(list, myComparator);
//descending
Collections.sort(list, new ReverseOrder(myComparator));