I have the following class:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
public class Sorter {
    private List<Pair<Long, NameDTO>> dtoPairs = new ArrayList<>();
    public Sorter() {
        Comparator<Pair<Long, NameDTO>> bySize = Comparator.comparing(Pair::getLeft);
        Comparator<Pair<Long, NameDTO>> byName = Comparator.comparing(p -> p.getRight().getName());
        dtoPairs.sort(bySize.reversed().thenComparing(byName));
    }
}
class NameDTO {
    private String name;
    public String getName() {
        return name;
    }
}
This compiles with no problems. However, if I try to inline the variables like this:
 dtoPairs.sort(Comparator.comparing(Pair::getLeft).reversed().thenComparing(Comparator.comparing(p -> p.getRight().getName())));
I get the following compilation error:
Sorter.java:[18,51] incompatible types: cannot infer type-variable(s) T,U
    (argument mismatch; invalid method reference
      method getLeft in class org.apache.commons.lang3.tuple.Pair<L,R> cannot be applied to given types
        required: no arguments
        found: java.lang.Object
        reason: actual and formal argument lists differ in length)
How can I write this expression to make Java understand the parameters correctly?
You need to tell the compiler the type of the generic parameters. Try this:
dtoPairs.sort(
    Comparator.comparing(Pair<Long, NameDTO>::getLeft)
    .reversed()
    .thenComparing(Comparator.comparing(p -> p.getRight().getName())));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With