美文网首页
lambda表达式

lambda表达式

作者: 劳资爱学习 | 来源:发表于2019-08-20 11:30 被阅读0次
 public static void main(String[] args) {

        Demo demo = new Demo();
        /**
         * 传入a ,b 两个参数,对a,b两个参数进行运算
         */
        // 类型声明
        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 = " + Demo.operate(10, 5, addition));
        System.out.println("10 - 5 = " + Demo.operate(10, 5, subtraction));
        System.out.println("10 x 5 = " + Demo.operate(10, 5, multiplication));
        System.out.println("10 / 5 = " + Demo.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);
    }

    public static int operate(int a, int b, MathOperation mathOperation){
        return mathOperation.operation(a, b);
    }
    //输出
    // 10 + 5 = 15
    //10 - 5 = 5
    //10 x 5 = 50
    //10 / 5 = 2
    //Hello Runoob
    //Hello Google

相关文章

网友评论

      本文标题:lambda表达式

      本文链接:https://www.haomeiwen.com/subject/bpwusctx.html