Java企业教程系列

Java8的Lambda和排序

  对数组和集合进行排序是Java 8 lambda令人惊奇的一个应用,我们可以实现一个Comparators来实现各种排序。看下面案例:

static class Person {

    final String firstName;

    final String lastName;

 

    Person(String firstName, String lastName) {

        this.firstName = firstName;

        this.lastName = lastName;

    }

 

    @Override

    public String toString() {

        return "Person{" +

                "firstName='" + firstName + '\'' +

                ", lastName='" + lastName + '\'' +

                '}';

    }

}

Person的数据有:

List<Person> people =

Arrays.asList(

    new Person("Jane", "Henderson"),

    new Person("Michael", "White"),

    new Person("Henry", "Brighton"),

    new Person("Hannah", "Plowman"),

    new Person("William", "Henderson")

);

我们希望根据名字排序(last name),然后再根据姓(first name)排序。

在Java 7之前,我们通常是通过实现一个Comparator:

people.sort(new Comparator<Person>() {

  @Override

  public int compare(Person o1, Person o2) {

    int result = o1.lastName.compareTo(o2.lastName);

 

    if (result == 0)

      result = o1.firstName.compareTo(o2.firstName);

 

    return result;

  }

});

people.forEach(System.out::println);

而在Java 8中,我们可以使用lambda替代匿名函数,如下:

Comparator<Person> c = (p, o) -> p.lastName.compareTo(o.lastName);

 

c = c.thenComparing((p, o) -> p.firstName.compareTo(o.firstName));

 

people.sort(c);

people.forEach(System.out::println);

在这里,Lambda表达式 (p, o) -> p.lastName.compareTo(o.lastName)替代之前的匿名函数new Comparator<Person>() {}

因为Java编译器并不能推迟对Lambda表达式类型判断,比如延迟到将comparator传递到sort()方法,因此使得我们进行链式Comparator书写有点困难,比如我们想写成如下:

XXX.thenComparing((p, o) -> p.lastName.compareTo(o.lastName))
       .thenComparing((p, o) -> p.firstName.compareTo(o.firstName))

换句话说,类型判断是从左到右,而不是从右到左,我们可以通过创建一个泛型来进行类型推断:

class Utils {

    static <E> Comparator<E> compare() {

        return (e1, e2) -> 0;

    }

}

通过上面的compare()方法,我们可以书写流畅的comparator链:

people.sort(

    Utils.<Person>compare()

         .thenComparing((p, o) ->

              p.lastName.compareTo(o.lastName))

         .thenComparing((p, o) ->

              p.firstName.compareTo(o.firstName))

);

 

people.forEach(System.out::println);

 

本文译自Java8 Friday系列,源码Gihub

Closure Lambda和Monad

Java 8教程

函数编程

 

 

猜你喜欢