温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Lambda基础语法

发布时间:2020-08-01 21:22:20 来源:网络 阅读:518 作者:孤魂1996 栏目:编程语言

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);
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI