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