Return a `Comparator` from another function

You can instantiate a Comparator<...> using a lambda expression:

public Comparator<Point> slopeOrder() {
    return (a, b) -> {
        // code here
    };
}

Here, a and b are the points to be compared.

Or if you're below java 8, you'd have to use an anonymous class:

public Comparator<Point> slopeOrder() {
    return new Comparator<Point>() {
        @Override
        public int compare(Point a, Point b) {
            // code here
        }
    };
}

If the Comparator is statless, you could create 1 instance and save it as a static final field, and just always return that instance.

Of course you can also take the long way around and create a new class that implement Comparator<Point>, and instantiate that class instead.


Since the description of the slopeOrder() method is:

compare two points by slopes they make with this point

That means you need to compare the values returned by calling slopeTo(Point that) on each object. Given that the return value of that method is a double, it means that you need to call Double.compare().

In pre-Java 8, you'd implement it using an anonymous class:

public Comparator<Point> slopeOrder() {
    return new Comparator<Point>() {
        @Override
        public int compare(Point o1, Point o2) {
            return Double.compare(slopeTo(o1), slopeTo(o2));
        }
    };
}

In Java 8, that's much simpler to write as a lambda expression:

public Comparator<Point> slopeOrder() {
    return (o1, o2) -> Double.compare(slopeTo(o1), slopeTo(o2));
}

Or using a method reference:

public Comparator<Point> slopeOrder() {
    return Comparator.comparingDouble(this::slopeTo);
}

In all cases, the slopeTo() calls are made on the this object of the slopeOrder() call.