Java中Lambda表达式

https://blog.csdn.net/renfufei/article/details/24600507

 

超过3行的逻辑就不适用Lambda表达式了。虽然看着很先进,其实Lambda表达式的本事只是一个“语法糖”,由于编译器推断并帮你转换包装为常规的代码,因此你可以使用更少的代码来实现同样的功能。本人建议不要乱用,因为这就和某些很高级的黑客写的代码一样,简洁,难懂,难以调试,维护人员想骂娘。

 

import java.util.Arrays;
import java.util.List;

public class LambdaTest {
    public static void main(String args[]){
        String[] app = {"张三","李四","王五","赵四","霍元甲"};
        List<String> persons = Arrays.asList(app);
        for (String person:persons){
            System.out.println(person+";");
        }
        persons.forEach((person)-> System.out.println(person+";"));
        persons.forEach(System.out::println);
    }
//        LambdaTest tester = 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 = " + 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-11-10 21:09  alittlecomputer  阅读(68)  评论(0编辑  收藏  举报