java8新特性

1.lamda表达式

lamda表达式主要用于替代匿名内部类,如常用的comparator匿名类:

public static void main(String[] args) {
        List list = Lists.newArrayList("a", "c", "b", "d");
        Comparator comp = (first, second) -> first.compareTo(second); //常规lamda
        Comparator comp1 = Comparator.comparing(e -> e); //简化方法

        Collections.sort(list, comp);
        Collections.sort(list, comp1);

        System.out.println(list);

    /**
    *使用stream的sort()或者
     Collections的sort() 
         ----Lambda表达式
    */
        Collections.sort(personList, (o1, o2) -> o1.getAge().compareTo(o2.getAge()));
        personList.stream().sorted((o1, o2) -> o1.getAge().compareTo(o2.getAge()));
        Collections.sort(personList, Comparator.comparing(Person::getAge));
    /**
    * 如果需要多条件排序,thenComparing(),对于排序完的结果还可以接着操作
    */
    List collect =                 personList.stream().sorted(Comparator.comparing(Person::getAge).thenComparing(Comparator.            comparing(Person::getName))).collect(Collectors.toList());


}

 

你可能感兴趣的:(java基础)