Lambda表达式的格式

2019-01-25  本文已影响0人  simit

Lambda表达式本质上是一种语法糖,它支持函数式接口,即有且仅有一个抽象方法的接口,常用@FunctionalInterface标签标识。
Lambda表达式一般的写法是:

(参数) -> {返回值;}

1.抽象接口无参数无返回值:

@FunctionalInterface
    interface test1 {
        public void run();
    }
test1 t1 = () -> System.out.println("");

2.抽象接口只有一个参数:

  @FunctionalInterface
    interface test1 {
        public void run(String x);
    }
test1 t1 = (x) -> System.out.println("");

3.抽象接口只有一个参数时,参数的小括号可以省略:
第二点可以写成

 test1 t1 = x -> System.out.println("");

4.Lambda体只有一条语句时,return与大括号均可省略:

   @FunctionalInterface //该接口中只能定义一个方法
    interface test {
        public String run(String string);
    }


    static class Person {
        public String goWalking(String string) {
            return "";
        }
    }
test t = (x) -> { return new Person().goWalking(x);};

可以写成:

test t = (x) -> new Person().goWalking(x);

方法引用:
格式:对象(类):: 方法名
注意事项:
1.被引用的方法的参数列表和函数式接口中的抽象方法的参数一致
2.当接口的抽象方法没有返回值,引用的方法可以有返回值也可以没有返回值
3.接口中的抽象方法有返回值,引用的方法必须有相同类型的返回值
方法引用:其实就是用一个接口的子类对象去接受方法引用返回的对象,此时只需要保证接口方法的参数和返回值必须和调用方法的返回值和参数一致。

 @FunctionalInterface //该接口中只能定义一个方法
    interface test {
        public String run(String string);
    }
//定义一个对象
  class Person {
//引用方法的参数和返回值和抽象方法一致
        public String goWalking(String string) {
            return "";
        }
    }

Lambda写法:

        Person person = new Person();
        //获取接口的子类对象
        test t2 = person::goWalking;
        System.out.println(t2.run("对象"));

转变为正常写法:

        Person person = new Person();
        test t2 = new test() {
            @Override
            public String run(String string) {
                return person.goWalking(string);
            }
        };
        System.out.println(t2.run("对象"));
上一篇 下一篇

猜你喜欢

热点阅读