How to sort a class using Comparator.comparing () depending on the specified criteria

I got the following class, which is not compiled code. I want to send criteria as a parameter to sort an array of employees. How to do this using Comparator.comparing () in the functional style of Java 8? For example, I want to sort it by name or by age, etc.

public class Employee {
        String name;
        int age;
        double salary;
        long mobile;    
}


public class EmpolyeeSorter {
    Employee[] employees = new Employee[]{
            new Employee("John", 25, 3000.0, 9922001),
            new Employee("Ace", 22, 2000.0, 5924001),
            new Employee("Keith", 35, 4000.0, 3924401)};


    public static void sortEmpoyeeByCriteria(Function<? super T, ? extends U> byCriteria) {
        Comparator<Employee> employeeComparator
                = Comparator.comparing(byCriteria);

    }
}
+4
source share
2 answers

You are missing the definition of your method:

public static <T, U extends Comparable<? super U>> void sortEmpoyeeByCriteria(Function<? super T, ? extends U> byCriteria) {
        Comparator<T> c = Comparator.comparing(byCriteria);
}

You must also pass Listthis method, which you want to sort in this case.

Collections.sort List Comparator ():

Collections.sort(yourList, Comparator.comparing(Employee::getXXX))

:

public static <T, U extends Comparable<? super U>> void sortEmpoyeeByCriteria(
            List<T> list,
            Function<? super T, ? extends U> byCriteria) {
        Comparator<? super T> c = Comparator.comparing(byCriteria);
        list.sort(c);
}
+4

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


    Comparator<Employee> comparingAge = Comparator.comparing(Employee::getAge);
    Comparator<Employee> comparingName = Comparator.comparing(Employee::getName);
    Comparator<Employee> comparingSalary = Comparator.comparing(Employee::getSalary);

    Arrays.sort(employees, comparingAge);
    System.out.println(Arrays.toString(employees));

    Arrays.sort(employees, comparingName);
    System.out.println(Arrays.toString(employees));

    Arrays.sort(employees, comparingSalary);
    System.out.println(Arrays.toString(employees));
}

:

    sortMe(employees, comparingAge);
    sortMe(employees, comparingName);
    sortMe(employees, comparingSalary);

sortme:

private static void sortMe(Employee[] employees, Comparator<Employee> comparingCriteria) {
    Arrays.sort(employees, comparingCriteria);
}
+1

Source: https://habr.com/ru/post/1685029/


All Articles