使用Java 8的功能样式比较器

时间:2016-01-28 23:49:49

标签: java comparator functional-interface

大家好,让我先告诉我,我还没有完成这段代码。我从互联网上找到了这个,并且使用比较器作为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);
    }
}

0 个答案:

没有答案