如何在 Java 8 中定义一个将 lambda 作为参数的方法? [英] How do I define a method which takes a lambda as a parameter in Java 8?

查看:8
本文介绍了如何在 Java 8 中定义一个将 lambda 作为参数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 8 中,方法可以创建为 Lambda 表达式,并且可以通过引用传递(需要做一些工作).网上有很多创建 lambda 表达式并与方法一起使用的示例,但没有关于如何创建将 lambda 作为参数的方法的示例.它的语法是什么?

In Java 8, methods can be created as Lambda expressions and can be passed by reference (with a little work under the hood). There are plenty of examples online with lambdas being created and used with methods, but no examples of how to make a method taking a lambda as a parameter. What is the syntax for that?

MyClass.method((a, b) -> a+b);


class MyClass{
  //How do I define this method?
  static int method(Lambda l){
    return l(5, 10);
  }
}

推荐答案

Lambda 纯粹是一个调用站点构造:Lambda 的接收者不需要知道 Lambda 的参与,而是接受一个具有适当的接口方法.

Lambdas are purely a call-site construct: the recipient of the lambda does not need to know that a Lambda is involved, instead it accepts an Interface with the appropriate method.

换句话说,您定义或使用一个函数式接口(即具有单个方法的接口),它接受并返回您想要的内容.

In other words, you define or use a functional interface (i.e. an interface with a single method) that accepts and returns exactly what you want.

为此Java 8在java.util.function(感谢 Maurice Naftalin 提供有关 JavaDoc 的提示).

For this Java 8 comes with a set of commonly-used interface types in java.util.function (thanks to Maurice Naftalin for the hint about the JavaDoc).

对于这个特定用例,有 java.util.function.IntBinaryOperator一个int applyAsInt(int left, int right)方法,这样你就可以编写你的方法像这样:

For this specific use case there's java.util.function.IntBinaryOperator with a single int applyAsInt(int left, int right) method, so you could write your method like this:

static int method(IntBinaryOperator op){
    return op.applyAsInt(5, 10);
}

但是您也可以定义自己的界面并像这样使用它:

But you can just as well define your own interface and use it like this:

public interface TwoArgIntOperator {
    public int op(int a, int b);
}

//elsewhere:
static int method(TwoArgIntOperator operator) {
    return operator.op(5, 10);
}

然后以 lambda 作为参数调用该方法:

Then call the method with a lambda as parameter:

public static void main(String[] args) {
    TwoArgIntOperator addTwoInts = (a, b) -> a + b;
    int result = method(addTwoInts);
    System.out.println("Result: " + result);
}

使用您自己的界面的优势在于您可以使用更清楚地表明意图的名称.

Using your own interface has the advantage that you can have names that more clearly indicate the intent.

这篇关于如何在 Java 8 中定义一个将 lambda 作为参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆