常用的函数式接口Function接口默认方法andThen

package com.chunzhi.Test07Function;

import java.util.function.Function;

/*
    Function接口中的默认方法andThen:用来进行组合操作

    需求:
        把String类型的“123”,转换为Integer类型,把转换后的结果加10
        把增加之后的Integer类型的数据,转换为String类型
 */
public class Test02Function_andThen {
    /*
        定义一个方法
        参数传一个字符串类型的数组
        参数再传递两个Function接口
            一个泛型使用Function<String, Integer>
            一个泛型使用Function<Integer, String>
     */
    public static void change(String s, Function<String, Integer> fun1, Function<Integer, String> fun2) {
        String ss = fun1.andThen(fun2).apply(s);
        System.out.println(ss);
    }

    public static void main(String[] args) {
        // 定义一个字符串
        String s1 = "123";
        // 调用change方法,传递字符串和两个Lambda表达式
        change(s1, (String str) -> {
            // 把字符串转换为整数+10
            return Integer.parseInt(str) + 10;
        }, (Integer i) -> {
            // 把整数转换为字符串。
            return i + ""; // 字符串和整数的求和时:把整数当作字符串,返回结果是两个字符串的拼接
        });
        // 使用Lambda表达式
        change(s1, str -> Integer.parseInt(str) + 10, i -> i + "");
    }
}

 

posted @ 2020-12-01 20:44  春志  阅读(523)  评论(0编辑  收藏  举报