Lambda 表达式的基础语法

1、基础语法

java8引入新的操作符“->”箭头操作符,箭头操作符将Lambda表达式分成两部分

左侧:Lambda 表达式的参数列表,对应抽象方法的参数列表

右侧:需要执行的功能,对应抽象方法要实现的功能

2、秘诀

左右遇一括号省, 左侧推断类型省,

3、语法格式

语法格式一:无参数,无返回值

() ->System.out.println("Hello");

   @Test
    public void test1() {
        int num = 2;//jdk 1.7前,必需是final,才能被同级调用
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello" + num);
            }
        };
        r.run();

        System.out.println("---------------------");
        //使用Lambda表达式
        Runnable r2 = () -> System.out.println("Hello Lambda");
        r2.run();
    }

语法格式二:有一个参数,无返回值

    @Test
    public void test2() {
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("有一个参数");
    }

语法格式三:若只有一个参数,小括号可以省略不写

    @Test
    public void test2() {
        Consumer<String> con = x -> System.out.println(x);
        con.accept("有一个参数");
    }

语法格式四:有两个参数,有返回值,并且Lambda体中有多条语句

  @Test
    public void test4() {
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
    }

语法格式五:有两个参数,有返回值,并且Lambda体内只有一条语句,              return 和{}都可以不写

    @Test
    public void test5() {
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

    }

语法格式六:Lambda 表达式的参数列表中数据类型可以省略不写,

                      因为JVM编译器通过上下文推断出,数据类型,即“类型推断”

                      (Integer x,Integer y) -> Intrger.compare(x,y);

4、Lambda 表达式需要“函数式接口”的支持

函数式接口:接口中只有一个抽象方法的接口,可用@FunctionalInterface修饰,可以检查是否是函数式接口

//接口,只有一个参数,有返回值的接口
package
Clock; @FunctionalInterface public interface MyFun { public Integer getValue(Integer x); }
 //需求:对一个数进行运算
    @Test
    public void test7() {
        Integer num = operation(100, x -> x * x);
        System.out.println(num);
        System.out.println(operation(200, y -> y + 200));

    }

    public Integer operation(Integer num, MyFun my) {
        return my.getValue(num);
    }

猜你喜欢

转载自www.cnblogs.com/wangxue1314/p/12756186.html