Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement reverseOrder() method using Comparator<T>?

I have been analyzing with Comparator interface in Java SE 8. Now, I am interested to know that how could I use reverseOrder() method using a class which implements the Comparator<T> interface. I wrote to a example program to check that out.

class NaturalOrderString implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        // TODO Auto-generated method stub
        return o1.compareTo(o2);
    }               
} 

public class App {
  public static void main(String[] args) { 
      Comparator<String> mycom= new NaturalOrderString();

      mycom.reverseOrder(); // can't use this
   }
}

So, now I should be able to use all the methods associated with Comparator Interface. But surprisingly whey I type mycom. then there comes no suggestion for reverseOrder() method. Why ? The class NaturalOrderString implements Comparator<T> .

So, I should accept mycom object to access reverseOrder() method. Isn't it ?

Moreover, I came to know that sorting in lists are occurred using natural ordering. So, using the Collection class I could access reverseOrder() method. So, preceding my example I could happily write

Collections.reverseOrder(mycom); // that's fine.

But my question is why I can't use reverseOrder() using a object of a class which implements Comparator<T> ? And, since we can't access it why Java include reverseOrder()method in Comparator<T> interface ?

Or, if it's really possible to access reverseOrder() through mycom object regarding my code, please give me an example of it.


1 Answers

Basically a lot of magic is possible here.

In order to reverse sorting, you simply need to "reverse" the result of the comparation.

You can study these foils. They are written in German, but there isn't much text there - and the code is all java. The presentation gives some lambda basics; to then explain how you can use lambdas and method references to develop a whole system where you sort/reverse sort streams; using "accessor" objects to retrieve whatever properties from the things you intend to sort.

For example leading to:

interface Comparator<T> {
  public int compare(T a, T b);
  public default Comparator<T> reversed() {
    return (a, b) –> compare(b, a) ;
}

Now one can implement that interface, and reverse sorting comes for free.

like image 185
GhostCat Avatar answered Sep 17 '26 04:09

GhostCat