Java如何将双函数作为参数传递

Java如何将双函数作为参数传递,java,lambda,Java,Lambda,我需要你帮我弄清楚如何通过这个双功能 BiFunction<Integer, List<Integer>, Integer> func = (a, b) -> { int result = 0; int temp = 0; for(Integer ele : b) { temp = b.get(ele); result += temp; }

我需要你帮我弄清楚如何通过这个双功能

BiFunction<Integer, List<Integer>, Integer> func = (a, b) -> {
        int result = 0;
        int temp = 0;
        for(Integer ele : b) {
            temp = b.get(ele);
            result += temp;
        }
        return a + result;
    };
BiFunction func=(a,b)->{
int结果=0;
内部温度=0;
对于(整数元素:b){
温度=b.get(ele);
结果+=温度;
}
返回+结果;
};
我正在使用这个junit测试

void testFoldLeft() {
        LinkedList<Integer> l = new LinkedList<>();
        for(int i = 0; i < 10; i++) l.addFirst(i+1);
        Integer u = fp.foldLeft(0, l, func(0,l));
    }
void testFoldLeft(){
LinkedList l=新建LinkedList();
对于(int i=0;i<10;i++)l.addFirst(i+1);
整数u=fp.foldLeft(0,l,func(0,l));
}
我试图通过foldLeft传递双函数func,如下所示

static <U,V> V foldLeft(V e, Iterable<U>l, BiFunction<V,U,V> f){
    return null;
}
static V foldLeft(ve、Iterablel、双功能f){
返回null;
}

func应该做的是获取一个列表,在本例中是b,将b中的所有元素相加,然后将该数字添加到a并返回结果。但是,Eclipse给了我一个错误,指出func是未定义的。我不熟悉双功能,所以我被困在这里了。我将感谢任何帮助

我认为不匹配是由于
foldLeft
的第二个参数声明不正确造成的。如果在您的示例中,
Integer
Iterable
的参数,那么您的方法应该这样声明:

static <U, V> V foldLeft(V e, Iterable<V> l, BiFunction<V, U, V> f) {
    return null;
}
Integer u = foldLeft(0, l, func);
不能在Java中调用表达式。除非将
func
声明为可见范围内的方法,
func()
将始终无效


请注意,您可以通过去掉
U
来简化泛型(我看不出这里对列表类型的类型变量有什么特殊的需求,但我可能缺少一些用例):


否则,调用
f.apply(e,l)
将失败,因为
Function
Function
不兼容。

我认为不匹配是由于
foldLeft
的第二个参数声明不正确造成的。如果在您的示例中,
Integer
Iterable
的参数,那么您的方法应该这样声明:

static <U, V> V foldLeft(V e, Iterable<V> l, BiFunction<V, U, V> f) {
    return null;
}
Integer u = foldLeft(0, l, func);
不能在Java中调用表达式。除非将
func
声明为可见范围内的方法,
func()
将始终无效


请注意,您可以通过去掉
U
来简化泛型(我看不出这里对列表类型的类型变量有什么特殊的需求,但我可能缺少一些用例):


否则,调用
f.apply(e,l)
将失败,因为
函数和
函数不兼容。

代码中有两个问题:

  • func(0,l)
    是一个语法错误,只需将
    func
    变量作为
    BiFunction
    传递即可。无需提供参数:

    Integer u = foldLeft(0, l, func);
    
  • foldLeft
    的泛型签名与
    BiFunction
    不匹配。根据当前的编写方式,
    Iterable l
    使编译器将
    U
    推断为
    整数
    ,因此编译器希望第三个参数是
    双函数
    ,而不是
    双函数
    。要使
    U
    LinkedList
    匹配,请按如下方式声明:

    static <U extends Iterable<V>, V> V foldLeft(V e, U l, BiFunction<V, U, V> f){
        return null;
    }
    

    这是在
    b
    的元素上循环,并将它们作为索引处理。我怀疑这是您想要的。

    您的代码中有两个问题:

  • func(0,l)
    是一个语法错误,只需将
    func
    变量作为
    BiFunction
    传递即可。无需提供参数:

    Integer u = foldLeft(0, l, func);
    
  • foldLeft
    的泛型签名与
    BiFunction
    不匹配。根据当前的编写方式,
    Iterable l
    使编译器将
    U
    推断为
    整数
    ,因此编译器希望第三个参数是
    双函数
    ,而不是
    双函数
    。要使
    U
    LinkedList
    匹配,请按如下方式声明:

    static <U extends Iterable<V>, V> V foldLeft(V e, U l, BiFunction<V, U, V> f){
        return null;
    }
    

    这是在
    b
    的元素上循环,并将它们作为索引处理。我怀疑这是你想要的。

    嘿!你能把整个测试课都贴出来吗?嘿!你能把整个测试课都贴出来吗?