Lambda纯粹是一个调用站点构造:Lambda的接收者不需要知道Lambda涉及到,而是接受具有适当方法的Interface。
换句话说,您定义或使用一个功能接口(即具有单个方法的接口)来接受并准确返回您想要的内容。
为此,Java
8附带了一组常用的接口类型
java.util.function(感谢Maurice
Naftalin提供有关JavaDoc的提示)。
对于此特定用例,
java.util.function.IntBinaryOperator只有一个
intapplyAsInt(int left, intright)方法,因此您可以这样编写
method:
static int method(IntBinaryOperator op){ return op.applyAsInt(5, 10);}但是您也可以定义自己的接口并像这样使用它:
public interface TwoArgIntOperator { public int op(int a, int b);}//elsewhere:static int method(TwoArgIntOperator operator) { return operator.op(5, 10);}使用您自己的界面的优点是您可以使用更清楚地表明意图的名称。



