Lambda基础语法

Lambda表达式的基本语法

java8中引入一个新的操作符“->”,该操作符称为箭头操作符或Lambda操作符。
操作符将Lambda表达式拆分为左右两部分:
左侧:Lambda表达式的参数列表
右侧:Lambda表达式中所需执行的功能,称为Lambda体

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

() -> System.out.println("Hello e路纵横开发团队");

@Test
    public void test1(){

        int num = 0;
        //匿名内部类
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World!" + num);//在匿名内部类中应用了同级别的变量时,在jdk1.7以前,变量必须申明为final,在jdk1.8中,默认加上final
            }
        };
        r.run();

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

        //Lambda表达式
        Runnable r1 = () -> System.out.println("Hello e路纵横开发团队" + num);
        r1.run();
    }

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

(x) -> System.out.prinrln(x);

@Test
    public void test2(){
        Consumer<String> consumer = (x) -> System.out.println(x);
        consumer.accept("e路纵横");
    }

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

x -> System.out.println(x);

@Test
    public void test3(){
        Consumer<String> consumer = x -> System.out.println(x);
        consumer.accept("e路纵横");
    }

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

Comparator<Integer> comparator = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
}

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

语法格式五:若Lambda体中只有一条语句,return和大括号都可以省略不写

Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);

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

语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器可以通过上下文推断出数据类型,即“类型推断”。

(Integer x, Integer y) -> Integer.compare(x, y); 其中Integer可以省略不写

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

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解@FunctionInterface修饰,可以检查接口是否是函数式接口

@FunctionalInterface
public interface MyFun<T> {

    public Integer getValue(Integer num);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章