当前位置: 代码迷 >> 综合 >> Lambda(六)--复合Lambda
  详细解决方案

Lambda(六)--复合Lambda

热度:65   发布时间:2023-12-29 03:56:46.0

Lambda复合意味着我们可以将多个简单的Lambda表达式组合而成一个新的复杂的表达式。在此函数式接口中虽然用到了不止一个方法,但其余的都是默认方法不是抽象方法,函数式接口定义的抽象方法一定只有一个。

本篇总结其中的比较器复合,谓词复合,函数复合

一、比较器复合

我们之前对苹果按照重量排序时,曾经写过:

List<Apple> inventor =  Arrays.asList(new Apple(80,"green"),new Apple(155, "green"),new Apple(155, "orange"),new Apple(120, "red"));	inventor.sort(Comparator.comparing(Apple::getWeight)); 

如果逆序呢?接口 有一个默认方法reversed可以使给定的比较器逆序。因此仍然用开始的那个比较器,只需要略作修改。

inventor.sort(Compartor.comparing(Apple::getWeight).reversed())

如果先按重量逆序再按照颜色排序呢,比较器里还提供了thenComparing()方法。

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

输出结果为:

Apple{color='green', weight=155}, Apple{color='orange', weight=155}, Apple{color='red', weight=120}, Apple{color='green', weight=80}

二、谓词复合

谓词主要有 negate,and,or三种,分别是非、与、或。and 和 or 方法是按照在表达式链中的位置,从左向右确定优 先级的。因此,a.or(b).and(c)可以看作(a || b) && c。 
举列  1.非红色的苹果

	    Predicate<Apple> redApple = a->a.getColor().equals("red");Predicate<Apple> notRedApple = redApple.negate();

与则是 and(),或则是or

三、函数复合

可以把Function接口所代表的Lambda表达式复合起来。Function接口为此配 了andThen和compose两个默认方法,它们都会返回Function的一个实例。如 g(f(x)):

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); 

f(g(x)):

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); 

(可见《Java8 实战》p60)