Direct comparator in Java out of the box

Posted by KARASZI István on Stack Overflow See other posts from Stack Overflow or by KARASZI István
Published on 2010-06-02T10:02:52Z Indexed on 2010/06/02 10:13 UTC
Read the original article Hit count: 240

I have a method which needs a Comparator for one of its parameters. I would like to pass a Comparator which does a normal comparison and a reverse comparator which does in reverse.

java.util.Collections provides a reverseOrder() this is good for the reverse comparison, but I could not find any normal Comparator.

The only solution what came into my mind is Collections.reverseOrder(Collections.reverseOrder()). but I don't like it because the double method calling inside.

Of course I could write a NormalComparator like this:

public class NormalComparator<T extends Comparable> implements Comparator<T> {
    public int compare(T o1, T o2) {
        return o1.compareTo(o2);
    }
}

But I'm really surprised that Java doesn't have a solution for this out of the box.

© Stack Overflow or respective owner

Related posts about java

Related posts about collections