最近发现了Lambda表达式比较有意思的事情,有的Lambda表达式居然可以组合起来使用。例如Comparator, Function 和 Predicate 函数接口提供了复合的方法。
Comparator
如果要把一群人按照年龄进行排序,那么可以这样做
personList.sort(Comparator.comparing(Person::getAge));
但是如果年龄一样的人如何排序呢,可以再按照名字进行排序
personList.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
这里使用了thenComparing()
方法把Lambda表达式进行了复合,表示先通过年龄进行排序,然后再根据名字进行排序。
如果还需要按照年龄进行反向排序呢?可以这样做
personList.sort(Comparator.comparing(Person::getAge).reversed().thenComparing(Person::getName));
Predicate
Predicate<T>是用来条件判断的,它支持and(与),or(或),negate(非)的Lambda表达式复合。
// 年龄大于18的人
Predicate<Person> p1 = person -> person.getAge() > 18;
// 年龄小于等于18的人
Predicate<Person> p2 = p1.negate();
// 年龄大于18且小于28的人
Predicate<Person> p3 = p1.and(person -> person.getAge() < 28);
Function
Function<T, R>是把T类型对象转化为R类型对象,它有compose和andThen两个复合方法。
例如现在有两个Function对象
// 执行加1操作
Function<Integer, Integer> add1 = i -> i + 1;
// 执行乘以2操作
Function<Integer, Integer> multiply2 = i -> i * 2;
使用compose和andThen效果如下
// 先加1,再乘以2
Function<Integer, Integer> f = add1.andThen(multiply2);
// 先乘以2,再加1
Function<Integer, Integer> g = add1.compose(multiply2);
原来就是执行顺序的差异。
一点想法
这里复合方法的原理其实比较简单,猜测并且看看源码就知道,在实际中要活学活用。