0

大家好,让我先让我清楚我还没有完成这段代码。我从互联网上找到了这个,它使用比较器进行了更好和更干净的排序,因为它是 java 8 函数式编程的新手,我想知道给定代码中的流程是如何流动的。请有人解释一下这段代码是如何工作的。谢谢 :)

@SuppressWarnings("rawtypes")
public class EmployeeInfoBest {
    static enum SortMethod {BYNAME, BYSALARY};
    final Function<Employee, String> byName = e -> e.getName();
    final Function<Employee, Integer> bySalary = e -> e.getSalary();

    final static class Pair<S,T> {
        Pair(S f, T t) {
            first = f;
            second = t;
        }
        S first;
        T second;
    }

    final Pair<Function,Function> byNamePair
      = new Pair<>(byName, bySalary);
    final Pair<Function,Function> bySalaryPair
      = new Pair<>(bySalary, byName);

    @SuppressWarnings("serial")
    final HashMap<SortMethod, Pair<Function,Function>> sortDiscriminator =
      new HashMap<SortMethod, Pair<Function,Function>>() {
        {
                put(SortMethod.BYNAME, byNamePair);
                put(SortMethod.BYSALARY, bySalaryPair);
        }
    };

    @SuppressWarnings("unchecked")
    public void sort(List<Employee> emps, final SortMethod method) {
        Collections.sort(emps, 
                Comparator.comparing(sortDiscriminator.get(method).first)
                          .thenComparing(sortDiscriminator.get(method).second));

    }

    public static void main(String[] args) {
        List<Employee> emps = new ArrayList<>();
        emps.add(new Employee("Joe", 100000));
        emps.add(new Employee("Tim", 50000));
        emps.add(new Employee("Andy", 60000));
        EmployeeInfoBest ei = new EmployeeInfoBest();
        ei.sort(emps, EmployeeInfoBest.SortMethod.BYNAME);
        System.out.println(emps);
        //same instance
        ei.sort(emps, EmployeeInfoBest.SortMethod.BYSALARY);
        System.out.println(emps);
    }
}
4

0 回答 0