zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    SQL SERVER 2012修改数据库名称(包括 db.mdf 名称的修改)
    vmware三种网络模式
    指针
    linux 中 开放端口,以及防火墙的相关命令
    数据库备份的脚本,记录下,还需优化下
    遍历 目录的几种有效办法
    转。git 乌龟的使用安装
    centos 时区正确,时间不对
    locate
    从 零开始 无差错 装好nginx+PHP
  • 原文地址:https://www.cnblogs.com/wangxue1314/p/12756186.html
Copyright © 2011-2022 走看看