Comparator.comparing with two arguments to the lambda

Viewed 3742

I wrote my custom comparator in non java 8 way as below, but not clear even after reading some blogs, how to do it using Comparator.comparing with the lambda style syntax.

class MyCustomComparator  implements Comparator<Integer> {
    @Override
    public int compare(Integer n1, Integer n2) {
        String ns1 = Integer.toString(n1) + Integer.toString(n2);
        String ns2 = Integer.toString(n2) + Integer.toString(n1);
        if (Integer.parseInt(ns1) > Integer.parseInt(ns2)) {
            return 1;
        } else if (Integer.parseInt(ns1) < Integer.parseInt(ns2))
            return -1;
        return 0;
    }
}

Generally Comparator.comparing takes the lambda where most examples I say the lamda is not taking argument.

2 Answers

The Comparator.comparing allows you to specify a transformation to be applied to each object individually before comparing them. Since your Comparator requires both arguments in order to apply its logic, you cannot write it as a Comparator.comparing expression.

The Comparator.comparing… factory methods are suitable for creating comparators comparing transformed values or properties of the elements to compare, but not when you have to combine both values.

But you can still implement you comparator using a lambda expression without the factory method

Comparator<Integer> myCustomComparator = (n1, n2) -> {
    String ns1 = "" + n1 + n2, ns2 = "" + n2 + n1;
    return Integer.compare(Integer.parseInt(ns1), Integer.parseInt(ns2));
};
Related