Lambda 表达式

(一)  Java8新特性

  1 Lambda 表达式,也可称为闭包,他是推动Java8发布的最重要的新特性

  2 Lambda允许把函数作为一个方法的参数(函数作为参数传递到方法中)

  3 使用Lambda表达式可以使代码变的更加简洁紧凑


(二)  示例 

/**
 * @author zhangchaocai
 * @create 2020-04-14 19:44
 */
public class LambdaTest {

    public static void main(String[] args) {

        LambdaTest test = new LambdaTest();

        //类型申明
        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 =" + test.operator(10,5,addition));
        System.out.println("10 - 5 =" + test.operator(10,5,subtraction));
        System.out.println("10 * 5 =" + test.operator(10,5,multiplication));
        System.out.println("10 / 5 =" + test.operator(10,5,division));


        //不用括号
        GreetingService service1 = message -> System.out.println(message);

        //用括号
        GreetingService service2 = (message) -> System.out.println(message);


        service1.sayMessage("service1   能够握紧的就别放了");

        service2.sayMessage("service2   时间着急着冲刷着");

    }

    interface MathOperation {
        int operation(int a,int b);
    }

    interface GreetingService {
        void sayMessage(String message);
    }

    private int operator(int a, int b,MathOperation mathOperation){
        return mathOperation.operation(a,b);
    }
}

  

    学以致用,方能致远

原文地址:https://www.cnblogs.com/misscai/p/12700993.html