除了 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 */