如何定义在Java 8中将lambda作为参数的方法?

时间:2012-11-28 12:06:32

标签: java lambda java-8

在Java 8中,方法可以创建为Lambda表达式,并且可以通过引用传递(通过一些工作)。有大量的在线示例,lambdas被创建并与方法一起使用,但没有关于如何使用lambda作为参数的方法的示例。这是什么语法?

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


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

14 个答案:

答案 0 :(得分:208)

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

换句话说,您定义或使用功能接口(即具有单个方法的接口),接受并准确返回您想要的内容。

为此,Java 8在java.util.function中附带了一组常用的接口类型(感谢Maurice Naftalin提供有关JavaDoc的提示)。

对于这个特定用例,java.util.function.IntBinaryOperatora single int applyAsInt(int left, int right) method,因此您可以像这样写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);
}

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

答案 1 :(得分:55)

要使用Lambda表达式,您需要创建自己的功能接口或使用Java功能接口进行需要两个整数并返回值的操作。 IntBinaryOperator

使用用户定义的功能界面

interface TwoArgInterface {

    public int operation(int a, int b);
}

public class MyClass {

    public static void main(String javalatte[]) {
        // this is lambda expression
        TwoArgInterface plusOperation = (a, b) -> a + b;
        System.out.println("Sum of 10,34 : " + plusOperation.operation(10, 34));

    }
}

使用Java功能界面

import java.util.function.IntBinaryOperator;

public class MyClass1 {

    static void main(String javalatte[]) {
        // this is lambda expression
        IntBinaryOperator plusOperation = (a, b) -> a + b;
        System.out.println("Sum of 10,34 : " + plusOperation.applyAsInt(10, 34));

    }
}

我创建的其他示例是here

答案 2 :(得分:34)

对于参数不超过2个的函数,可以在不定义自己的接口的情况下传递它们。例如,

class Klass {
  static List<String> foo(Integer a, String b) { ... }
}

class MyClass{

  static List<String> method(BiFunction<Integer, String, List<String>> fn){
    return fn.apply(5, "FooBar");
  }
}

List<String> lStr = MyClass.method((a, b) -> Klass.foo((Integer) a, (String) b));

BiFunction<Integer, String, List<String>> 中,IntegerString是其参数,List<String>是其返回类型。

对于只有一个参数的函数,您可以使用 Function<T, R> ,其中 T 是其参数类型, { {1}} 是其返回值类型。有关Java已提供的所有接口,请参阅此page

答案 3 :(得分:14)

http://lambdafaq.org/lambda-resources链接的是一个支持Lambda的Java 8 JavaDocs的公共Web可访问版本。 (这显然应该是对Joachim Sauer的答案的评论,但我无法通过我需要添加评论的声誉点进入我的SO帐户。)lambdafaq网站(我维护它)回答了这个以及很多其他Java -lambda问题。

注意:这个答案是在Java 8 GA文档成为publicly available之前编写的。不过,我已经离开了,因为Lambda FAQ对于了解Java 8中引入的功能的人来说可能仍然有用。

答案 4 :(得分:5)

对于任何使用此功能的人来说,一个好的方法就是使用java.util.function.BiConsumer。 例如:

Import java.util.function.Consumer
public Class Main {
    public static void runLambda(BiConsumer<Integer, Integer> lambda) {
        lambda.accept(102, 54)
    }

    public static void main(String[] args) {
        runLambda((int1, int2) -> System.out.println(int1 + " + " + int2 + " = " + (int1 + int2)));
    }

输出将是:166

答案 5 :(得分:4)

Lambda表达式可以作为参数传递。要将lambda表达式作为参数传递,参数的类型(接收lambda表达式作为参数)必须是函数接口类型。

如果有功能界面 -

interface IMyFunc {
   boolean test(int num);
}

并且有一个过滤方法只在大于5的情况下才在列表中添加int。注意这里过滤方法有函数接口IMyFunc作为参数之一。在这种情况下,lambda表达式可以作为方法参数的参数传递。

public class LambdaDemo {
    public static List<Integer> filter(IMyFunc testNum, List<Integer> listItems) {
        List<Integer> result = new ArrayList<Integer>();
        for(Integer item: listItems) {
            if(testNum.test(item)) {
                result.add(item);
            }
        }
        return result;
    }
    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<Integer>();
        myList.add(1);
        myList.add(4);
        myList.add(6);
        myList.add(7);
        // calling filter method with a lambda expression
        // as one of the param
        Collection<Integer> values = filter(n -> n > 5, myList);

        System.out.println("Filtered values " + values);
    }
}

答案 6 :(得分:3)

对我来说,最有意义的解决方案是定义一个Callback接口:

interface Callback {
    void call();
}

,然后将其用作您要调用的函数中的参数:

void somewhereInYourCode() {
    method(() -> {
        // You've passed a lambda!
        // method() is done, do whatever you want here.
    });
}

void method(Callback callback) {
    // Do what you have to do
    // ...

    // Don't forget to notify the caller once you're done
    callback.call();
}

不过只是精度

lambda不是特殊的接口,类或您可以自己声明的其他任何东西。 Lambda只是为() -> {}特殊语法指定的名称,当将单方法接口作为参数传递时,可以提高可读性。它旨在替代此:

method(new Callback() {
    @Override
    public void call() {
        // Classic interface implementation, lot of useless boilerplate code.
        // method() is done, do whatever you want here.
    }
});

因此,在上面的示例中,Callback 不是 lambda,它只是一个常规接口; lambda是可用于实现它的快捷方式语法的名称。

答案 7 :(得分:2)

您可以使用上面提到的功能接口。 下面是一些示例

Function<Integer, Integer> f1 = num->(num*2+1);
System.out.println(f1.apply(10));

Predicate<Integer> f2= num->(num > 10);
System.out.println(f2.test(10));
System.out.println(f2.test(11));

Supplier<Integer> f3= ()-> 100;
System.out.println(f3.get());

希望有帮助

答案 8 :(得分:1)

嗯,这很容易。 lambda表达式的目的是实现功能接口。它是只有一种方法的接口。 Here is awesone article about predefined and legacy functional interfaces.

无论如何,如果你想实现自己的功能界面,那就去做吧。仅举几个例子:

public interface MyFunctionalInterface {
    String makeIt(String s);
}

所以让我们创建一个类,我们将在其中创建一个接受 MyFunctionalInterface 类型的方法:

public class Main {

    static void printIt(String s, MyFunctionalInterface f) {
        System.out.println(f.makeIt(s));
    }

    public static void main(String[] args) {

    }
}

您应该做的最后一件事是将 MyFunctionalInterface 的实现传递给我们定义的方法:

public class Main {

    static void printIt(String s, MyFunctionalInterface f) {
        System.out.println(f.makeIt(s));
    }

    public static void main(String[] args) {
        printIt("Java", s -> s + " is Awesome");
    }
}

那就是它!

答案 9 :(得分:1)

Lambda不是一个对象,而是一个功能接口。 可以使用@FuntionalInterface作为注释定义尽可能多的功能接口

@FuntionalInterface
public interface SumLambdaExpression {
     public int do(int a, int b);
}

public class MyClass {
     public static void main(String [] args) {
          SumLambdaExpression s = (a,b)->a+b;
          lambdaArgFunction(s);
     }

     public static void lambdaArgFunction(SumLambdaExpression s) {
          System.out.println("Output : "+s.do(2,5));
     }
}

输出如下

Output : 7

Lambda表达式的基本概念是定义您自己的逻辑但已经定义了Arguments。因此,在上面的代码中,您可以将do函数的定义从添加到任何其他定义更改,但您的参数仅限于2.

答案 10 :(得分:1)

基本上要传递lamda表达式作为参数,我们需要一种可以容纳它的类型。就像整数值一样,我们保存在原始 int 或Integer类中。 Java没有用于lamda表达式的单独类型,而是使用接口作为类型来保存参数。但是该界面应该是功能界面

答案 11 :(得分:0)

执行以下操作..

您已声明method(lambda l) 您要做的就是创建一个名为lambda的接口并声明一个抽象方法

public int add(int a,int b);  

方法名称在这里无关紧要。

因此,当您致电MyClass.method( (a,b)->a+b)时 此实现(a,b)->a+b将注入到您的接口add方法中。因此,每当您调用l.add时,它将采用此实现并执行ab和{{ 1}}将返回return l.add(2,3)。 -基本上这就是lambda所做的。.

答案 12 :(得分:-1)

以下是C#处理此问题的大致方式(但表示为Java代码)。这样的事情几乎可以满足您的所有需求:

import static org.util.function.Functions.*;

public class Test {

    public static void main(String[] args)
    {
        Test.invoke((a, b) -> a + b);       
    }

    public static void invoke(Func2<Integer, Integer, Integer> func)
    {
        System.out.println(func.apply(5, 6));
    }
}

package org.util.function;

public interface Functions {

    //Actions:
    public interface Action {
        public void apply();
    }

    public interface Action1<T1> {
        public void apply(T1 arg1);
    }

    public interface Action2<T1, T2> {
        public void apply(T1 arg1, T2 arg2);
    }

    public interface Action3<T1, T2, T3> {
        public void apply(T1 arg1, T2 arg2, T3 arg3);
    }

    public interface Action4<T1, T2, T3, T4> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    }

    public interface Action5<T1, T2, T3, T4, T5> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    }

    public interface Action6<T1, T2, T3, T4, T5, T6> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    }

    public interface Action7<T1, T2, T3, T4, T5, T6, T7> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    }

    public interface Action8<T1, T2, T3, T4, T5, T6, T7, T8> {
        public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
    }

    //Functions:
    public interface Func<TResult> {
        public TResult apply();
    }

    public interface Func1<T1, TResult> {
        public TResult apply(T1 arg1);
    }

    public interface Func2<T1, T2, TResult> {
        public TResult apply(T1 arg1, T2 arg2);
    }

    public interface Func3<T1, T2, T3, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3);
    }

    public interface Func4<T1, T2, T3, T4, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
    }

    public interface Func5<T1, T2, T3, T4, T5, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    }

    public interface Func6<T1, T2, T3, T4, T5, T6, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
    }

    public interface Func7<T1, T2, T3, T4, T5, T6, T7, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
    }

    public interface Func8<T1, T2, T3, T4, T5, T6, T7, T8, TResult> {
        public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
    }
}

答案 13 :(得分:-2)

使用lambda作为参数有灵活性。它支持java中的函数编程。基本语法是

  

param - &gt; method_body

以下是一种方法,您可以定义一个采用功能接口(使用lambda)作为参数的方法。 一个。如果您希望定义在功能接口内声明的方法, 比如,功能接口作为参数/参数提供给从main()调用的方法

@FunctionalInterface
interface FInterface{
    int callMeLambda(String temp);
}


class ConcreteClass{

    void funcUsesAnonymousOrLambda(FInterface fi){
        System.out.println("===Executing method arg instantiated with Lambda==="));
    }

    public static void main(){
        // calls a method having FInterface as an argument.
        funcUsesAnonymousOrLambda(new FInterface() {

            int callMeLambda(String temp){ //define callMeLambda(){} here..
                return 0;
            }
        }
    }

/***********Can be replaced by Lambda below*********/
        funcUsesAnonymousOrLambda( (x) -> {
            return 0; //(1)
        }

    }
  

FInterface fi =(x) - &gt; {return 0; };

     

funcUsesAnonymousOrLambda(FI);

     

上面可以看到,lambda表达式如何被接口替换。

上面解释了lambda表达式的特定用法,还有更多。 REF Java 8 lambda within a lambda can't modify variable from outer lambda