JAVA中Function的使用
package com; import java.util.function.Function; public class FuctionDemo { public static void main(String[] args) { convert("100",s -> Integer.parseInt(s),integer ->String.valueOf(integer+100)); } private static void convert(String s, Function<String,Integer> fun1,Function<Integer,String> fun2){ // Integer s1 = fun1.apply(s); // String s2 = fun2.apply(s1); // System.out.println(s2); String apply = fun1.andThen(fun2).apply(s); System.out.println(apply); } }
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 | package com; import java.util.function.Function; /** * 练习,String s = "张三,30"; * 1,将字符串截取得到数字年龄部分 * 2,将上一步的年龄字符串转换成int类型数据 * 3,将上一步的int数据加70,得到一个int结果,在控制台输出 */ public class FuctionDemo2 { public static void main(String[] args) { convert( "张三,30" ,s -> s.split( "," )[ 1 ],Integer::parseInt,integer -> integer+ 70 ); convert( "张三,30" ,s -> Integer.parseInt(s.split( "," )[ 1 ]),integer -> integer+ 70 ); convert( "张三,30" ,s -> Integer.parseInt(s.split( "," )[ 1 ])+ 70 ); } public static void convert(String s, Function<String,String>fun1,Function<String ,Integer>fun2,Function<Integer,Integer>fun3){ Integer apply = fun1.andThen(fun2).andThen(fun3).apply(s); System.out.println(apply); } public static void convert(String s, Function<String,Integer>fun1,Function<Integer ,Integer>fun2){ Integer apply = fun1.andThen(fun2).apply(s); System.out.println(apply); } public static void convert(String s, Function<String,Integer>fun1){ Integer apply = fun1.apply(s); System.out.println(apply); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步