4

这是我尝试过的。它甚至不编译。

public class LambdaExample {

    public static Integer handleOperation(Integer x, Integer y,  Function converter){
                return converter.apply(x,y);
    }

    public static void main(String[] args){
         handleOperation(10,10, Operation::add);
    }

}

class Operation {

    public int add(Integer x, Integer y){
        return x+y;
    }

}

我想在这里实现/学习的几件事是:

1)如何lambda expression作为方法参数传递(在上面的main方法中)

2)如何给函数传参( handleOpertion方法中,compilationapply只带一个参数的错误)

4

3 回答 3

5

AFunction接受输入 x 并产生结果 y。因此,您在执行 时不是在寻找 a Function(没有提到您使用了原始类型)return converter.apply(x,y);,而是在寻找 aBiFunction<Integer, Integer, Integer>或更简单的 a ,BinaryOperator<Integer>因为每个类型参数都是相同的。

1)如何将 lambda 表达式作为方法参数传递(在上面的 main 方法中)

通过提供一个尊重BinaryOperator<Integer>接口契约的 lambda 表达式,即一个将两个Integer作为参数并返回一个Integer.

handleOperation(10,10, (a, b) -> a + b)

2)如何给函数传参(handleOperation方法中,apply只带一个参数的编译错误)

因为函数的形式是f => u这样,所以 apply 方法接受一个参数并产生一个结果,就像一个数学函数,例如f(x) = 2 * x(参考答案的第一部分)。

这是我尝试过的。它甚至不编译。

要使您的代码编译,您可以将方法设为静态或在使用方法引用之前创建一个新实例。然后它会在调用函数的apply方法add时引用新实例的方法。handleOperation

handleOperation(10,10, new Operation()::add);

注意这个方法已经存在于 JDK 中,它是Integer::sum. 它需要两个原始 int 值而不是Integer引用,但它足够接近,因此自动装箱机制将使此方法有效以BinaryOperator<Integer>在方法上下文中显示为 a。

于 2015-05-27T23:06:16.650 回答
4

您的handleOperation方法需要一个实现的对象FunctionOperation::add(方法引用)不符合条件。此外,对于两个参数,您需要改为使用BiFunction

这是一个应该有效的示例:

public class LambdaExample {

    public static Integer handleOperation(Integer x, Integer y,  BiFunction<Integer, Integer, Integer> converter){
                return converter.apply(x,y);
    }

    public static void main(String[] args){
         handleOperation( 10,10, new Operation() ); // should return 20
    }

}

class Operation implements BiFunction<Integer, Integer, Integer> {

    public Integer apply(Integer x, Integer y){
        return x+y;
    }

}

更新:

public class LambdaExample {

    public static Integer handleOperation(Integer x, Integer y,  BiFunction<Integer, Integer, Integer> converter){
                return converter.apply(x,y);
    }

    public static void main(String[] args){
         handleOperation( 10,10, Operation::add ); // should return 20
    }

}

class Operation {

    public static int add(Integer x, Integer y){
        return x+y;
    }

}
于 2015-05-27T22:53:56.217 回答
3

您的 Function 参数是原始的(无类型),应该是 BiFunction。

尝试这个:

public static Integer handleOperation(Integer x, Integer y,  BiFunction<Integer, Integer, Integer> converter){
    return converter.apply(x,y);
}

具有所有 3 种类型的 BiFunction 可以用(单类型)BinaryOperator 替换:

public static Integer handleOperation(Integer x, Integer y,  BinaryOperator<Integer> converter){
    return converter.apply(x,y);
}

要调用它,您可以这样做:

int sum = handleOperation(1, 2, (x, y) -> x + y); // 3

实际上,您已经实施了reduce。这个调用同样可以写成:

int sum = Stream.of(1, 2).reduce((x, y) -> x + y);
于 2015-05-27T23:06:42.703 回答