util.function--函数Function

13 篇文章 0 订阅
public class FunctionTest {

    @Test
    public void test() {
        // int 转 str
        Function<Integer, String> int2Str = String::valueOf;
        // 平方
        Function<String, Integer> square = e -> {
            int i = Integer.parseInt(e);
            return i * i;
        };
        // 格式输出
        Function<String, Date> format = e -> new Date();

        String apply = int2Str.apply(5);
        // note: apply 实际传入的参数类型取决于compose,这里前置函数需要String类型,所以传入"5"
        // note: andThen 的函数入参必须是apply的return类型
        Date apply2 = int2Str
                .compose(square) // 前置处理: apply执行前,先计算平方
                .andThen(format) // 后置处理: apply执行后,格式化输出
                .apply("5"); // 处理


        System.out.println(apply);
        System.out.println(apply2); //
    }

    @Test
    public void test2() {
        List<String> names = List.of("Alice", "Bob", "Charlie");

        // note 定义可扩展的方法,处理逻辑动态传入. 使用Function.identity()进行占位
        List<String> processedNames = processList(names, Function.identity());

        System.out.println(processedNames); // 输出: [Alice, Bob, Charlie]
    }

    public static <T> List<T> processList(List<T> list, Function<T, T> processor) {
        List<T> result = new ArrayList<>();
        for (T item : list) {
            result.add(processor.apply(item)); // 应用处理函数
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值