Java排序如何工作?

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

我了解它会返回List< T>但是< T是什么,U扩展了Comparable&lt ;?超级U>&gt ;?

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

解决方法:

答案就在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扩展了Comparable&lt ;?超级U>是静态方法中的类型参数(静态T> void someMethod(U objectOfTypeU)),该参数具有Comparator.comparing()方法所需的某些范围.它还允许您使用(通用)类型T作为返回值(即List< T>).

上一篇:java-在未知值之前对具有已知值的列表进行排序


下一篇:Java Comparator reversed()方法产生了奇怪的结果