天天看点

Java8: Lambda表达式语法

原文:Syntax of Lambda Expressions

一个Lambda表达式由下列结构组成:

  • 参数列表,像Java的方法中的参数列表,只不过没有类型,被圆括号括起来;
  • 一个箭头符号:->
  • 表达式的方法体,可以是一句话,也可以是多句话。
p -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25
           

Return语句并不是Lambda表达式的一部分,如果你要使用它,就必须用花括号({})括起来。

p -> {
    return p.getGender() == Person.Sex.MALE
        && p.getAge() >= 18
        && p.getAge() <= 25;
}
           

一个简单的例子:

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 addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}