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

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

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

比较器复合

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

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

1.逆序

接口有一个默认方法reversed可以使给定的比较器逆序。

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

2.比较器链

如果前一个条件相同的话,想通过第二个条件排序。thenComparing方法就是做这个用的。

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

谓词复合

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

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

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

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

猜你喜欢

转载自blog.csdn.net/zsx157326/article/details/80885726