Lambda in Java8

Lamda表达式又称为闭包 是JAVA8的新特性,它允许把函数作为参数传递到方法种
而且lamda表达式的写法可谓是相当方便 大大简化了函数的书写方式
There are some very important properties:
Optional datatype claim: we don’t need to claim the data type of parameters
Optional bracket of parameters: if we only have one parameter then we don’t need to use the bracket but if we don’t then sure we do
Optional statement bracket: if we only have one statement in the function, then we don’t need a bracket;
Optional return key value.

下面是几个例子 以后用到的话仿照他们去书写就可以了

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("Runoob");
      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);
   }
}

posted @ 2020-10-28 06:43  EvanMeetTheWorld  阅读(23)  评论(0)    收藏  举报