Function接口的默认方法和练习

Function接口——默认方法andThen

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

  把String类型的"123",转换为Integer类型,把转换后的结果加10

  把增加之后的Integer类型的数据,转换为String类型

分析:转换了两次

  第一次把String类型转换为了Integer类型

  所以我们可以使用Function<String,Integer> fun1

  Integer i = fun1.apply(“123”)+10;

  第二次把Integer类型转换为String类型

  所以我们可以使用Function<Integer,String> fun2

  String s = fun2.apply(i);

  我们可以使用andThen方法,把两次转换组合在一起使用

  String s = fun1.andThen(fun2).apply(“123”);

  fun1先调用apply方法,把字符串转换为Integer

  fun2再调用apply方法,把Integer转换为字符串

复制代码
    /*
        定义一个方法
        参数传一个字符串类型的整数
        参数再传递两个Function接口
            一个泛型使用Function<String,Integer>
            一个泛型使用Function<Integer,String>
     */
    public static void change(String s,Function<String,Integer> fun1,Function<Integer,String> fun2){
        String str = fun1.andThen(fun2).apply(s);
        System.out.println(str);
    }

    public static void main(String[] args) {
        //定义一个字符串类型的整数
        String s = "123";
        //调用change方法,传递字符串和两个Lambda表达式
//        change(s,(String str)->{
//            //那字符串转换为整数+10
//            return Integer.parseInt(str)+10;
//        },(Integer i)->{
//            //把整数转换为字符串
//            return i+"";
//        });
        //优化Lambda表达式
        change(s,str->Integer.parseInt(str)+10,i->i+"");
    }
复制代码

 

 

 

 

 

 

 

 

 

Function接口练习——自定义函数模型拼接

题目

请使用Function进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
String str = “张三,18”;
分析:

1.将字符串截取数字年龄部分,得到字符串;
Function<String,String> “张三,18”->“18”

2.将上一步的字符串转换称为int类型的数字
Function<String,Integer> “18”->18

3.将上一步的int数字累加100,得到结果int数字。
Function<Integer,Integer> 18->118

复制代码
    /*
        定义一个方法
        参数传递包含姓名和年龄的字符串
        参数再传递3个Function接口用于类型转换
     */
    public static int change(String s, Function<String, String> fun1, Function<String, Integer> fun2, Function<Integer, Integer> fun3) {
        //使用andThen方法把三个转换组合到一起
        return fun1.andThen(fun2).andThen(fun3).apply(s);
    }

    public static void main(String[] args) {
        //定义一个字符串
        String str = "张三,18";
        //调用change方法,参数传递字符串和3个Lambda表达式
        int num = change(str, (String s) -> {
            //“张三,18”->“18”
            return str.split(",")[1];
        }, (String s) -> {
            //“18”->18
            return Integer.parseInt(s);
        }, (Integer i) -> {
            //18->118
            return i + 100;
        });
        System.out.println(num);
    }
复制代码

 

  

 

posted @   xjw12345  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示