Java 使用reduce组合函数
我正在尝试使用以下代码使用reduce函数组合函数:Java 使用reduce组合函数,java,lambda,java-8,reduce,Java,Lambda,Java 8,Reduce,我正在尝试使用以下代码使用reduce函数组合函数: class CustomClass { private Function<Map<String, String>, Integer> cal; public CustomClass (Function<Map<String, String>, Integer>... func) { cal = Stream.of(func) .r
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);
}
}
class自定义类{
私有函数cal;
公共自定义类(函数…函数){
cal=流量(函数)
.reduce(Function.identity(),Function::and then);
}
}
但我得到了这个错误:
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)
方法reduce(函数,二进制运算符)
在类型流中不适用
对于参数(函数、函数::和)
我做错了什么?只有当第一个函数的结果与第二个函数所需的参数匹配时,才能组合两个函数。在您的示例中并非如此,因为您的
函数接受映射
,但返回一个整数
。不能将整数
作为参数传递给下一个函数
如果更改了函数的签名,则代码将通过编译
例如:
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自定义类{
私有函数cal;
公共自定义类(函数…函数){
cal=流量(函数)
.reduce(Function.identity(),Function::and then);
}
}
及
class自定义类{
私有函数cal;
公共自定义类(函数…函数){
cal=流量(函数)
.reduce(Function.identity(),Function::and then);
}
}
两个都通过了编译。明白了,我会按照requirement@vaydesalme除了问题本身没有说明的要求之外。从逻辑上考虑,根据输入和输出类型链接多个函数
有意义吗?你在那里需要瓦拉格吗?
class CustomClass {
private Function<Integer,Integer> cal;
public CustomClass (Function<Integer,Integer>... func) {
cal = Stream.of(func)
.reduce(Function.identity(), Function::andThen);
}
}