java8 lambda表达式 (1)
lambda表达式是java8中最强大的功能。其提供了函数式编程,大大简化开发。
语法
lambda表达式的语法为:参数->表达式体部分。
可选的类型声明:无需声明参数类型,编译器会根据参数值类型推断。
可选的包括参数的圆括号:单个参数无需圆括号,多个参数需要。
可选的花括号:表达式体部分,单条语句花括号可以省略。
可选return关键字:编译器根据表达式推断返回值;花括号表明表达式返回值。
示例:
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
//with type declaration
MathOperation addition = (int a, int b) ->a + b;
//with out type declaration
MathOperation subtraction = (a, b) ->a - b;
//with return statement along with curlybraces
MathOperationmultiplication = (int a, int b) -> { return a * b; };
//without return statement and withoutcurly braces
MathOperation division = (int a, int b) ->a / b;
System.out.println("10 + 5 = " +tester.operate(10, 5, addition));
System.out.println("10 - 5 = " +tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " +tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " +tester.operate(10, 5, division));
//with parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " +message);
//without parenthesis
GreetingService greetService2 = (message)->
System.out.println("Hello " +message);
greetService1.sayMessage("Mahesh");
greetService2.sayMessage("Suresh");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperationmathOperation){
return mathOperation.operation(a, b);
}
}
运行结果为:
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
总结:
² lambda表达式主要使用在需要定义内联实现接口,接口有单个方法。
² lambda表达式代替匿名类,实现简单强大的函数式编程。
继续阅读lambda表达式2。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/52335381