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

转载于:https://www.cnblogs.com/happyflyingpig/p/9094099.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值