Java 8 - Lambda expressions

Lambda allowed to function as an argument of a method (function as a parameter passed into the process).
Lambda expressions can make code more compact introduction.

grammar

(parameters) -> expression
或
(parameters) -> { statements; }

feature:

  • Optional type declaration: do not need to declare the parameter type, the compiler can be unified identification parameter value.
  • The optional parameters in parentheses: You can not add parentheses when a parameter, but need to add parentheses when multiple parameters or no parameters.
  • Optional braces: if only one statement, you can omit the braces.
  • Optional return keyword: If the subject is only one expression that returns a value, the compiler will automatically return value.

Examples

// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)

Variable Scope

Lambda expressions can only refer to the outer local variables final mark, that can not change the definition of local variables within the extraterritorial application of Lambda, otherwise compilation errors.

Lambda expressions specifically for the interface has only one method (ie function interface)

Lambda details
https://www.runoob.com/java/java8-lambda-expressions.html
https://www.cnblogs.com/andywithu/p/7357069.html

Guess you like

Origin www.cnblogs.com/tangjian07/p/12097489.html