复合 Lambda 表达式的有用方法

比较器复合

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。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容