Java 8: implementing Comparable

Viewed 6362

I like the new static factory methods of Comparator, as they allow to implement Comparators in a very concise and less error-prone way.

But what is the recommended way to implement Comparable? Should we use Comparators inside the Comparable implementation?

public MyClass implements Comparable<MyClass>{
...
    public int compareTo(MyClass other){
        Comparator<MyClass> naturalOrderComparator = 
            Comparator.comparing(MyClass::getFoo)
                      .thenComparing(MyClass::getBar);
        return naturalOrderComparator.compare(this, other);
    } 
}

or even use a static comparator to reduce a lot of object creation when sorting huge collections:

public MyClass implements Comparable<MyClass>{
    private static final Comparator<MyClass> NATURAL_ORDER_COMPARATOR =     
        Comparator.comparing(MyClass::getFoo)
                  .thenComparing(MyClass::getBar);

    ...

    public int compareTo(MyClass other){
        return NATURAL_ORDER_COMPARATOR.compare(this, other);
    } 
}

Or is there another recommended way to implement Comparable with Java SE 8?

2 Answers
Related