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);
    }
}

 

posted @   phpwyl  阅读(6387)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示