Java8-函数复合用法
JDK8自带的函数式接口Function有两个默认方法andThen和compose,它们都返回Function的一个实例,可以用这两个方法把Function接口所代表的的Lambda表达式复合起来。
先看个简单的例子:
Function<Integer, Integer> f = x -> x + 1; Function<Integer, Integer> g = x -> x * 2; // andThe用法 Function<Integer, Integer> h = f.andThen(g); // (2+1)*2 = 6 System.out.println(h.apply(2)); // (5+1)*2=12 System.out.println(h.apply(5)); //compose用法 Function<Integer, Integer> p = f.compose(g); //(3*2)+1=7 System.out.println(p.apply(3)); //(9*2)+1=19 System.out.println(p.apply(9));
简单的应用
package org.burning.sport.javase.lambda.chapter3.function; public class Letter { public static String addHeader(String text) { return "From ZhejiangHZ " + text; } public static String addFooter(String text) { return "Sign YingjieLi " + text; } public static String checkSpell(String text) { return text.replace("li", "zhang"); } }
/** * 实际的应用一下 */ Function<String, String> header = Letter::addHeader; Function<String, String> pipeLine = header.andThen(Letter::addFooter).andThen(Letter::checkSpell); System.out.println(pipeLine.apply("wangying")); Function<String, String> pipeLine2 = header.compose(Letter::addFooter); System.out.println(pipeLine2.apply("jiahao"));
https://gitee.com/play-happy/base-project
参考:
【1】《Java8实战》