zoukankan      html  css  js  c++  java
  • 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实战》

  • 相关阅读:
    提取文件唯一标识符
    U盘出现很多.exe的文件处理方案
    winform做的excel与数据库的导入导出
    php获取数据库结构
    根据手机屏幕的旋转,调整图片
    c#中base64编码解码
    遮罩层的实现
    opencv车流量统计算法
    winform创建快捷方式
    mysql存储过程中like用法
  • 原文地址:https://www.cnblogs.com/happyflyingpig/p/9094099.html
Copyright © 2011-2022 走看看