Java8新特性之Lambda(2)

除了 Runnable,Comparator等常用函数式接口,为了推动函数式编程,Java8又在 java.util.function 包下为我们提供了大量好用的函数式,因为基本数据类型不能抽象成对象,所以可以看到有大量Double,Int,Long前缀的接口,我们只看比较核心的:

接口名抽象方法描述符
Predicate   boolean test(T t)   T -> boolean  
BiPredicate<T, U>   test(T t, U u)   ( T, U ) -> boolean  
Consumer   void accept(T t)   T -> void  
BiConsumer<T, U>   void accept(T t, U u)   ( T, U ) -> void  
Function<T, R>   R apply(T t)   T -> R  
BiFunction<T, U, R>   R apply(T t, U u)   ( T, U ) -> R  
Supplier   T get()   void -> T  
复合Lambda#

令人惊喜的是,java8提供的函数式接口还有许多好用的default方法,可以让我们把多个Lambda复合起来,组成流水线。拿用的比较多的Function接口举例,我们要写一封邮件,我们关注的是信的内容

Function<String, String> writeEmailHeader = text -> "Hi ," + "\n" + text; Function<String, String> writeEmailText = text -> text + "\n"; Function<String, String> writeEmailFooter = text -> text + "BRs" + "\n" + "Chen"; Function<String, String> writeEmail = writeEmailHeader.andThen(writeEmailText).andThen(writeEmailFooter); System.out.println(writeEmail.apply("I will take half day sick leave today")); /** * 输入如下: * Hi , * I will take half day sick leave today * BRs * Chen */

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f8de08253c012c3cea94dd1eb6ca67f2.html