常用的函数式接口_Function接口_默认方法andThen和练习_自定义函数模型拼接
常用的函数式接口_Function接口_默认方法andThen
Function接口中有一个默认的andThen方法,用来进行组合操作
该方法同样用于“先做什么,再做什么”的场景,和Consumer中的andThen差不多:
第一个操作是将字符串解析成为int数字,第二个操作是乘以10。两个操作通过andThen按照前后顺序组合到了一起。
需求:
把String类型的“123”,转换为Inteter类型,把转换后的结果加10
把增加之后的Integer类型的数据,转换为String类型
public class DFunction_andThen { 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+""; }); } 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); } }
常用的函数式接口_Function接口练习_自定义函数模型拼接
使用Function进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
String str = "张三,18";
1.将字符串截取数字年龄部分,得到字符串;
2.将上一步的字符串转换成为int类型的数字;
3.将上一步的int数字累加100,得到结果int数字。
public class DTest04 { public static void main(String[] args) { String str = "张三,20"; int num = change(str,(String s)->{ return s.split(",")[1]; },(String s)->{ return Integer.parseInt(s); },(Integer i)->{ return i+100; }); System.out.println(num); } public static int change(String s, Function<String,String> fun1,Function<String,Integer> fun2,Function<Integer,Integer> fun3){ return fun1.andThen(fun2).andThen(fun3).apply(s); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix