Java8 new features -Lambda expression

Lambda expressions

Lambda expressions, also known as closures, it is to promote the most important new features of Java 8 release.

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.

Syntax contrast

Lambda expression syntax is as follows:

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

Important 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: 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.

Simple example:

// 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)
public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
 
      // 类型声明
      MathOperation addition = (int a, int b) -> a + b;
 
      // 不用类型声明
      MathOperation subtraction = (a, b) -> a - b;
 
      // 大括号中的返回语句
      MathOperation multiplication = (int a, int b) -> { return a * b; };
 
      // 没有大括号及返回语句
      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));
 
      // 不用括号
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
 
      // 用括号
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
 
      greetService1.sayMessage("Nowcoder");
      greetService2.sayMessage("Google");
   }
 
   interface MathOperation {
      int operation(int a, int b);
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
 
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}
执行输出结果:

```java
$ javac Java8Tester.java
$ java Java8Tester
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Nowcoder
Hello Google

Variable Scope

lambda expressions can only refer to the outer local variables final mark, which means that the definition of local variables can not be modified within the extraterritorial application of lambda, otherwise compilation errors.
Enter the following code in Java8Tester.java file:

public class Java8Tester {
 
   final static String salutation = "Hello! ";
 
   public static void main(String args[]){
      GreetingService greetService1 = message ->
      System.out.println(salutation + message);
      greetService1.sayMessage("Nowcoder");
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
}

The implementation of the above script, output is:

$ javac Java8Tester.java
$ java Java8Tester
Hello! Nowcoder

We can also access the local variables of the outer layer directly on the lambda expression:

public class Java8Tester {
    public static void main(String args[]) {
        final int num = 1;
        Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
        s.convert(2);  // 输出结果为 3
    }
 
    public interface Converter<T1, T2> {
        void convert(int i);
    }
}

Local variable lambda expressions can not be declared as final, but must not be modified later in the code (i.e., having a recessive semantic-final)

int num = 1; 
Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);
num = 5; 
//报错信息:Local variable num defined in an enclosing scope must be final or effectively
 final

In Lambda expressions which are not allowed to declare a local variable with the same name as parameters or local variables.

String first = ""; 
Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length());  //编译会出错

Other new features (Update)

Java8 new features - Method reference
Java8 new features - function interface
Java8 new features - the default method

Published 26 original articles · won praise 6 · views 2943

Guess you like

Origin blog.csdn.net/weixin_45676630/article/details/104884384