JAVA in -> Lambda function

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/exodus3/article/details/90511500

-> is Lambda expressions, also known as Lambda function, the new features of Java 8.

Here Insert Picture Description

Lambda can be read as "wave motor."
Lambda allowed to function as an argument of a method (function as a parameter passed into the process).
Lambda expressions can make use of the code becomes more simple and compact.

The basic syntax Lambda expressions:

(parameters) -> expression

(parameters) ->{ statements; }

The following are important characteristics of a lambda expression:

Optional type declaration: do not need to declare the parameter type, the compiler can be unified identification parameter value.
The optional parameters in parentheses: no need to define a parameter in parentheses, but a number of parameters need to be defined parentheses.
Optional braces: if the body contains a statement, you do not need to use braces.
Optional return keyword: If the subject is only one expression that returns a value, the compiler will automatically return value, braces need to specify clear expression that returns a value

Lambda expressions Examples of
simple example Lambda expressions:
a:

    // 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)

two:

String[] days = {" Monday", "Tuesday",  
       "Wednesday", "Thursday",
       "Friday",  "Saturday",    
       "Sunday"};  
List<String> allDays =  Arrays.asList(days);  
  
// 以前的循环方式  
for (String allDay : allDays) {  
     System.out.print(allDay + "; ");  
}  
  
// 使用 lambda 表达式以及函数操作(functional operation)  
allDays.forEach((allDay) -> System.out.print(allDay + "; "));  
   
// 在 Java 8 中使用双冒号操作符(double colon operator)  
allDays.forEach(System.out::println);  

These three are the same output

We usually write for loop, use a lambda expression form will be different, but the result is the same. The code looks a little on the high force grid.

//双冒号运算操作符是类方法的句柄,lambda表达式的一种简写  
方法调用
person -> person.getAge();
可以替换成
Person::getAge

x -> System.out.println(x)
可以替换成
System.out::println

Lambda function briefly summarize the advantages and disadvantages
advantages: simplicity, reduce code redundancy
Disadvantages: difficult to understand, difficult to debug

With more words, you get used to it.

Guess you like

Origin blog.csdn.net/exodus3/article/details/90511500