Java 8-Lambda表达式-复合Lambda表达式

Java 8的好几个函数式接口都有为方便而设计的方法。具体而言,许多函数式接口,好比Comparator、Predicate和Function等函数式接口都有几个能够用来结合Lambda表达式的默认方法。java

这意味着你能够把多个简单的Lambda复合成复杂的表达式。好比,你能够让两个谓词之间作一个or操做,组合成一个更大的谓词。并且,你还能够让一个函数的结果成为另外一个函数的输入。web

比较器复合

能够使用静态方法Comparator.comparing,根据提取用于比较的键值的Function来返回一个Comparator。app

Comparator<Apple> c=Comparator.comparing(Apple::getWeight);

1.逆序svg

接口有一个默认方法reversed能够使给定的比较器逆序。函数

invertory.sort(comparing(Apple::getWeight).reversed);

2.比较器链spa

若是前一个条件相同的话,想经过第二个条件排序。thenComparing方法就是作这个用的。设计

inventory.sort(comparing(Apple::getWeight))
         .reversed()
         .thenComparing(Apple::getCountry));

谓词复合

谓词接口包括三个方法:negate、and和or,让你能够重用已有的Predicate来建立更复杂的谓词。好比,你能够使用negate方法来返回一个Predicate的非,好比苹果不是红的。code

Predicate<Apple> notRedApple=redApple.negate();

把两个Lambda用and方法组合起来xml

Predicate<Apple> redAndHeavyApple=redApple.and(a->a.getWeight()>50);
Predicate<Apple> redAndHeavyAppleOrGreen=redApple.and(a->a.getWeight()>150)
    .or(a->"green".equals(a.getColor()));

函数复合

还能够把Function接口所表明的Lambda表达式复合起来。Function接口为此配了andThen和compose两个默认方法,它们都会返回Function的一个实例。排序

andThen方法会返回一个函数,它先对输入应用一个给定函数,再对输出应用另外一个函数。好比,假设有一个函数f给数字加1(x->x+1),另外一个函数g给数字乘2,你能够将它们组合成一个函数h,先给数字加1,再给结果乘2。

Function<Integer,Integer> f=x->x+1;
Function<Integer,Integer> g=x->x*2;
Function<Integer,Integer> h=f.andThen(g);
int result=h.apply(1);//4

也能够相似地使用compose方法,先把给定的函数用做compose的参数里面给的那个函数,而后再把函数自己用于结果。

Function<Integer,Integer> f=x->x+1;
Function<Integer,Integer> g=x->x*2;
Function<Integer,Integer> h=f.compose(g);
int result=h.apply(1);//3