复合 Lambda 表达式的有用方法

2021-09-08  本文已影响0人  JESiller

比较器复合

Comparator<Apple> c = Comparator.comparing(Apple::getWeight);
inventory.sort(comparing(Apple::getWeight).reversed());
inventory.sort(comparing(Apple::getWeight) 
 .reversed() 
 .thenComparing(Apple::getCountry));
Predicate<Apple> redAndHeavyAppleOrGreen = 
 redApple.and(a -> a.getWeight() > 150) 
 .or(a -> "green".equals(a.getColor()));

函数复合

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。

上一篇 下一篇

猜你喜欢

热点阅读