posts - 397,comments - 0,views - 25332

java.util.function.Function<T,R>接口用来根据一个类型的数据得到另一个类型的数据,

前者称为前置条件,后者称为后置条件。

Function接口中最主要的抽象方法为:R apply(T t),根据类型T的参数获取类型R的结果。

使用的场景例如:将String类型转换为Integer类型

分析:

  定义一个方法

  方法的参数传递一个字符串类型的整数

  方法的参数传递一个Function接口,泛型使用<String,Integer>

  使用Function接口中的方法apply,把字符串类型的整数,转换为Integer类型的整数

 

 

实现:

复制代码
public static void change(String s, Function<String,Integer> fun){
        int apply = fun.apply(s);
        System.out.println(apply);
    }

    public static void main(String[] args) {
        String s = "1234";
        change(s,(String str)->{
            return Integer.parseInt(str);
        });

        change(s,str->Integer.parseInt(str));


    }
复制代码

 

 

 

 

 

 

 

常用的函数式接口_Function接口和默认方法AndThen



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

需求:

  把String类型的"123",转换为Inteter类型,把转换后的结果加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转换为字符串

实现:

 

 

 

 

posted on   淤泥不染  阅读(83)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示