如何让Comparator.comparing正确推断类型参数?

时间:2017-02-02 08:20:11

标签: java generics

我有以下课程:

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;
    }
}

这没有任何问题。但是,如果我尝试内联这样的变量:

 dtoPairs.sort(Comparator.comparing(Pair::getLeft).reversed().thenComparing(Comparator.comparing(p -> p.getRight().getName())));

我收到以下编译错误:

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)

如何编写此表达式以使Java正确理解参数?

2 个答案:

答案 0 :(得分:5)

您需要告诉编译器通用参数的类型。 试试这个:

SELECT L.*, ED.emname , EM.emmobile 
FROM leaves L INNER JOIN
employee_details ED ON L.emid = ED.emid
WHERE L.emid = @emid

答案 1 :(得分:2)

这句话编译得很好:

dtoPairs.sort(Comparator.comparing((Pair<Long, NameDTO> p) -> p.getLeft())
                        .reversed()
                        .thenComparing(Comparator.comparing(p -> p.getRight().getName())));

...指出了你的编译原因:当你进行方法引用(Pair:getLeft)时,Pair是原始的,它的类型参数被简单地忽略。这使得thenComparing(...)方法期望Comparator<Pair, Object>