码迷,mamicode.com
首页 > 编程语言 > 详细

JavaSE-Java8-函数复合用法

时间:2018-05-26 20:29:53      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:默认方法   head   ring   pipeline   pre   应用   pack   blank   方法   

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实战》

JavaSE-Java8-函数复合用法

标签:默认方法   head   ring   pipeline   pre   应用   pack   blank   方法   

原文地址:https://www.cnblogs.com/happyflyingpig/p/9094099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!