Java 8中的Lambda

Lambda是什么,就是没有名字的函数。

Lambda的语法

  • A comma-separated list of formal parameters enclosed in parentheses.

  • The arrow token, ->

  • A body, which consists of a single expression or a statement block.

下面是有两个参数的Lambda的例子。

public class Calculator {

    interface IntegerMath {
        int operation(int a, int b);   
    }

    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }

    public static void main(String... args) {

        Calculator myApp = new Calculator();
        IntegerMath multi = (a, b) -> a * b;
        IntegerMath divide = (a, b) -> a / b;
        System.out.println("40 * 2 = " +
            myApp.operateBinary(40, 2, multi ));
        System.out.println("20 / 10 = " +
            myApp.operateBinary(20, 10, divide));    
    }
}

http://jdk8.java.net/download.html
下载jdk8,然后安装。我下载的是Linux 64位的,只需要解压就可以使用。

在使用之前需要设置环境变量export PATH=~/download/jdk1.8.0/bin/:$PATH,然后编译和运行;

[jdk1.8.0]$ javac Calculator.java
[jdk1.8.0]$ java Calculator
40 * 2 = 80
20 / 10 = 2

如果我们把

myApp.operateBinary(40, 2, multi )

改成

myApp.operateBinary(40, 2, (a, b) -> a *b)

也时可以的。但是JDK时如何知道我们的Lambda就是IntegerMath呢?

答案时JDK不知道,它只是将Lambda转成IntegerMath然后使用的。这就是Target Typing。

To determine the type of a lambda expression, the Java compiler uses the
target type of the context or situation in which the lambda expression was
found. It follows that you can only use lambda expressions in situations in
which the Java compiler can determine a target type:

  • Variable declarations

  • Assignments

  • Return statements

  • Array initializers

  • Method or constructor arguments

  • Lambda expression bodies

  • Conditional expressions, ?:

  • Cast expressions

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html