Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Java sorting work?

The following code is working fine. But I can't understand how it works? Could you please explain? Especially the method signature of sortEmployeeByCriteria (see below).

I understood it returns List<T> but what is <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;
}
like image 287
masiboo Avatar asked Jul 17 '26 16:07

masiboo


1 Answers

The answer lies in the first line of the sortEmployeeByCriteria():

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

Looking at the documentation of Comparator.comparing() (a static method, same as 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.

So the <T, U extends Comparable<? super U>> is a type parameter in a static method (static <T> void someMethod(U objectOfTypeU)), which has some bounds required by the Comparator.comparing() method. It also allows you to use (generic) type T as a return value (i.e. List<T>).

like image 141
syntagma Avatar answered Jul 19 '26 07:07

syntagma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!