You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为含Function属性的FunctionCompose类实现flatMap方法?

实现FunctionCompose的flatMap方法

这里是完成flatMap方法实现后的完整代码:

import java.util.function.Function;

class FunctionCompose<T, R> {
    public final Function<T, R> function;

    public FunctionCompose(Function<T, R> function) {
        this.function = function;
    }

    public <U> FunctionCompose<T, U> map(Function<? super R, ? extends U> mapper) {
        return new FunctionCompose<>(function.andThen(mapper));
    }

    public <U> FunctionCompose<T, U> flatMap(Function<? super R, ? extends FunctionCompose<? super R, ? extends U>> mapper) {
        Function<T, U> combinedFunction = t -> {
            R result = function.apply(t);
            return mapper.apply(result).apply(result);
        };
        return new FunctionCompose<>(combinedFunction);
    }

    public R apply(T smth) {
        return function.apply(smth);
    }
}

实现说明

  1. 泛型与参数设计

    • <U>是flatMap最终返回结果的类型
    • 方法参数mapper使用Function<? super R, ? extends FunctionCompose<? super R, ? extends U>>,遵循PECS原则:
      • ? super R允许mapper接收R的父类类型参数,提升兼容性
      • ? extends FunctionCompose<? super R, ? extends U>允许mapper返回FunctionCompose的子类,且其输入可接受R的父类、输出可为U的子类
  2. 核心逻辑

    • 先通过原function将输入t转换为R类型结果
    • 用该结果调用mapper,得到一个新的FunctionCompose实例
    • 调用这个新实例的apply方法处理之前的R类型结果,得到最终的U类型值
    • 将整个逻辑包装为Function<T, U>,创建新的FunctionCompose返回

验证示例

用你提到的场景测试:

public class Test {
    public static void main(String[] args) {
        // String转Integer的FunctionCompose(取字符串长度)
        FunctionCompose<String, Integer> stringToInt = new FunctionCompose<>(String::length);
        
        // flatMap传入Integer->FunctionCompose<Integer, Integer>(将输入值乘2)
        FunctionCompose<String, Integer> composed = stringToInt.flatMap(i -> new FunctionCompose<>(x -> x * 2));
        
        // 输出:10("hello"长度为5,5*2=10)
        System.out.println(composed.apply("hello"));
    }
}

内容的提问来源于stack exchange,提问作者SendHelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 02:20:22