这个 Java 排序是如何工作的?

How does this Java sorting work?

以下代码运行良好。但我不明白它是如何工作的?你能解释一下吗?特别是 sortEmployeeByCriteria 的方法签名(见下文)。

我明白了returnsList<T>但是<T, U extends Comparable<? super U>>是什么?

public static void sortIt() {
    Employee[] employees = new Employee[] {
        new Employee("John", 25, 3000.0, 9922001),
        new Employee("Ace", 22, 20000.0, 5924001),
        new Employee("Keith", 35, 4000.0, 3924401)
    };

    List<Employee> employeeList  = Arrays.asList(employees);
    List<Employee> list = sortEmployeeByCriteria(employeeList, Employee::getName);
    list.stream().forEach(System.out::println);
}

// But could you please explain the method signature how is it working
public static <T, U extends Comparable<? super U>> List<T> sortEmployeeByCriteria( List<T> list, Function<? super T, ? extends U> byCriteria) {
    Comparator<? super T> comparator = Comparator.comparing(byCriteria);
    list.sort(comparator);
    return list;
}

它不是 lambda - 它是一个方法参考(Employee::getName 部分)。 sortEmployeeByCriteria 只是一个普通的通用静态方法,采用类型 T 的列表,以及采用 T(或子类)并生成类型 U(或子类)和 [=30= 的东西的 Function ] 类型为 T 的(已排序)列表。

不寻常的部分可能是 Comparator#comparing,它创建了一个比较器,它将根据给定的映射比较 Ts,即它转换 T,在你的例子中是 [=14] =],到 U,在你的例子中是 StringgetName 的结果),它知道如何比较,因为 String 实现了 Comparable。然后它继续使用 List#sort(Comparator).

对它们进行实际排序

Employee::getName 基本上是一个 shorthand,一个 method reference 你可以传递而不是创建你自己的 Function 实例。

答案就在sortEmployeeByCriteria()的第一行:

Comparator<? super T> comparator = Comparator.comparing(byCriteria);

查看 documentation of Comparator.comparing()(静态方法,与 sortEmployeeByCriteria() 相同):

static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor)

Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key.

因此 <T, U extends Comparable<? super U>>static 方法 (static <T> void someMethod(U objectOfTypeU)) 中的类型参数,它具有 Comparator.comparing() 方法所需的一些边界。它还允许您使用(通用)类型 T 作为 return 值(即 List<T>)。