【问题标题】:Combine Function using reduce使用reduce组合函数
【发布时间】:2020-03-26 04:57:54
【问题描述】:

我正在尝试使用以下代码使用reduce函数来组合函数:

class CustomClass {
    private Function<Map<String, String>, Integer> cal;

    public CustomClass (Function<Map<String, String>, Integer>... func) {
        cal = Stream.of(func)
                .reduce(Function.identity(), Function::andThen);
    }
}

但我收到此错误:

The method reduce(Function<Map<String,String>,Integer>, BinaryOperator<Function<Map<String,String>,Integer>>) 
 in the type Stream<Function<Map<String,String>,Integer>> is not applicable 
 for the arguments (Function<Object,Object>, Function::andThen)

我在这里做错了什么?

【问题讨论】:

    标签: java lambda java-8 reduce


    【解决方案1】:

    如果第一个函数的结果与第二个函数所需的参数匹配,则只能组合两个函数。在您的示例中并非如此,因为您的 Functions 接受 Map&lt;String, String&gt;,但返回 Integer。您不能将 Integer 作为参数传递给下一个 Function

    如果您更改了Functions 的签名,您的代码将通过编译。

    例如:

    class CustomClass {
        private Function<Map<String, String>, Map<String, String>> cal;
    
        public CustomClass (Function<Map<String, String>, Map<String, String>>... func) {
            cal =  Stream.of(func)
                    .reduce(Function.identity(), Function::andThen);
        }
    }
    

    class CustomClass {
        private Function<Integer,Integer> cal;
    
        public CustomClass (Function<Integer,Integer>... func) {
            cal =  Stream.of(func)
                    .reduce(Function.identity(), Function::andThen);
        }
    }
    

    都通过编译。

    【讨论】:

    • 知道了,我会根据要求修改代码
    • @vaydesalme 除了问题本身未说明的要求。从逻辑上考虑,根据输入和输出类型链接多个Function&lt;Map&lt;String, String&gt;, Integer&gt; 是否有意义?你甚至需要可变参数吗?
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2016-05-27
    • 2021-07-08
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2018-10-06
    相关资源
    最近更新 更多