常用的函数式接口_Function接口_默认方法andThen和Function接口练习_自定义函数模型拼接
默认方法:andThen
Function 接口中有一个默认的andThen 方法,用来进行组合操作。JDK源代码如:
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) ‐> after.apply(apply(t)); }
该方法同样用于“先做什么,再做什么”的场景,和Consumer 中的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转换为字符串
public class Demo02Function_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 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+""); } }
第一个操作是将字符串解析成为int数字,第二个操作是乘以10。两个操作通过andThen 按照前后顺序组合到了一起
请注意,Function的前置条件泛型和后置条件泛型可以相同
请使用Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
String str = "赵丽颖,20";
1. 将字符串截取数字年龄部分,得到字符串;
2. 将上一步的字符串转换成为int类型的数字;
3. 将上一步的int数字累加100,得到结果int数字。
解答
public class Demo03Test { /* 定义一个方法 参数传递包含姓名和年龄的字符串 参数再传递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 = "赵丽颖,20"; //调用change方法,参数传递字符串和3个Lambda表达式 int num = change(str,(String s)->{ //"赵丽颖,20"->"20" return s.split(",")[1]; },(String s)->{ //"20"->20 return Integer.parseInt(s); },(Integer i)->{ //20->120 return i+100; }); System.out.println(num); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)