函数式接口-常见函数式接口-Function接口
常见函数式接口
JDK提供了大量常用的函数式接口以丰富Lambda的经典使用常见 它们注意在java.util.function包中被提供
Function接口
Function<T,R>接口用于根据一个类型的数据得到另一个类型的数据 前者称为前置条件,后置条件
抽象方法:apply
Function接口中的最主要的抽象方法为
R apply(T t):根据类型T的参数获取类型R的结果
使用场景例如:将String类型转换为Integer类型
代码:
public class BFunction { /* 定义一个方法 方法的参数传递一个字符串类型的整数 方法的参数传递一个Function接口,泛型使用<String,Integer> 使用Function接口中的方法apply,把字符串类型的整数,转换为Integer类型的整数 */ public static void change(String s, Function<String,Integer> fun){ Integer apply = fun.apply(s); System.out.println(apply); } public static void main(String[] args) { //定义一个字符串类型的整数 String sp = "1234"; //调用change方法,传递字符串类型的整数,和Lambda表达式(优化Lambda) change(sp, (String spr)->Integer.parseInt(spr)); } }
默认方法:andThen
Function接口中有一个默认的andThen方法 用来进行组合操作
代码:
/* 定义一个方法 参数串一个字符串类的整数 参数在传递两个Funcion接口 一个泛型使用Function<String,Integer> 一个泛型使用Function<Integer,String> */ public static void cheng(String s, Function<String,Integer> fun1,Function<Integer,String> fun2){ String apply = fun1.andThen(fun2).apply(s); System.out.println(apply); } public static void main(String[] args) { //定义一个字符串 String sp = "123"; // //调用change方法 传递字符串和两个Lambda表达式 // cheng(sp, (String se)->{ // //把字符串转换为整数+10 // return Integer.parseInt(se)+10; // }, (Integer i)->{ // //把整数转换为字符串 // return i+""; // }); //优化Lambda表达式 cheng(sp, str->Integer.parseInt(str)+10, i->i+""); }
练习:自定义函数模型拼接
题目:
请使用Function进行函数模型的拼接 按照顺序需要执行的多个函数操作为:
Sting str="张三,20";
1.将字符串截取数字年龄部分 得到字符串
2.将上一步的字符串转换为int类型的数学
3.将上一步的int数字累加100 得到结果int数字
代码:
public class BFunction2 { /* 定义一个方法 参数传递包含名字和年龄的字符串 参数再传递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->200 return i+100; }); System.out.println(num); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix