• Java 8 新特性 什么是 Lambda 表达式,它的语法格式是什么,怎么使用 Lambda 表达式?


    什么是 Lambda 表达式

    Lambda 是一个匿名函数,我们可以把 Lambda 表达式理解为是一段可以可以传递的代码(将代码像数据一样传递)。

    可以写出更简洁更灵活的代码。作为一种更紧凑的的代码风格,使Java的语言表达能力得到了提升。

    Lambda 表达式的基础语法:

    Java 8中引入了一个新的操作符 “->” 该操作符称为箭头操作符或者Lambda操作符

    箭头操作符将Lambda表达式拆分成两部分:

    左侧:Lambda 表达式的参数列表

    右侧:Lambda 表达式中所需执行的功能,即Lambda体

    之前我们用匿名内部类实现接口,现在我们用Lambda实现接口

    Lambda表达式中左侧的参数列表对应接口中抽象方法的参数列表

    Lambda表达式中右侧就是你对接口中抽象方法需要实现的功能

    Lambda 表达式语法格式

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

    ()-> System.out.println("Hello Lambda!");
    
    • 1

    ● 语法格式一:具体案例实现

        @Test
        public void test1() {
            //匿名内部类实现
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    System.out.println("Hello World!");
                }
            };
            System.out.println("-------------------------------");
            //Lambda 表达式实现
            Runnable r1 = () -> System.out.println("Hello Lambda!");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

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

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

    ● 语法格式二: 具体案例实现,利用Consumer接口实现测试

        @Test
        public void test2() {
            Consumer<String> con = (x)-> System.out.println(x);
            con.accept("Lambda 表达式 yyds");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

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

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

    ● 语法格式四:有两个以上参数,有返回值,并且Lambda表达式有多条语句(当Lambda有多条语句,Lambda体必须使用大括号)

    ● 语法格式四:具体案例实现

        @Test
        public void test3() {
            Comparator<Integer> com = (x, y) -> {
                System.out.println("函数式接口");
                return Integer.compare(x,y);
            };
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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

        @Test
        public void test4() {
            Comparator<Integer> com = (x, y) ->
                    Integer.compare(x, y);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

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

    (Integer x, Integer y) ->  Integer.compare(x, y);
    
    • 1

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

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

    Java 四大核心函数式接口

    ● 四大核心函数式接口实现案例

    /**
     * Java 8 内置的四大核心函数式接口
     * Consumer: 消费型接口
     * void accept(T t);
     * 

    * Supplier:供给型接口 * T get(); *

    * Function:函数型接口 * R apply(T t); *

    * Predicate:断言型接口 * boolean test(T t); */ public class TestLambda4 { //Consumer: 消费型接口 @Test public void test1() { happy(10000, x -> System.out.println("刚哥喜欢大宝剑,每次花费" + x + "元")); } public void happy(double money, Consumer<Double> con) { con.accept(money); } //Supplier:供给型接口 @Test public void test2() { List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100)); for (Integer num : numList) { System.out.println(num); } } //需求:产生指定个数的整数,并且放入集合中 public List<Integer> getNumList(int num, Supplier<Integer> sup) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < num; i++) { Integer n = sup.get(); list.add(n); } return list; } // Function:函数型接口 @Test public void test3() { String newStr = strHandler("\t\t\t 我大尚硅谷威武", (str) -> str.trim()); System.out.println(newStr); String subStr = strHandler("我大尚硅谷威武", (sub) -> sub.substring(2, 5)); System.out.println(subStr); } //需求:用于处理字符串 public String strHandler(String str, Function<String, String> fun) { return fun.apply(str); } //Predicate:断言型接口 @Test public void test(){ List<String> list = Arrays.asList("Hello","atguigu","Lambda","www","ok"); List<String> strList = filterSrt(list, (s) -> s.length() > 3); for (String str : strList) { System.out.println(str); } } //需求:满足条件的字符串,放入集合中 public List<String> filterSrt(List<String> list, Predicate<String> pre) { List<String> newList = new ArrayList<>(); for (String str : list) { if (pre.test(str)) { newList.add(str); } } return newList; } }

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    其他接口

    Lambda 表达式练习

    1.调用Collections.sort()方法,通过定制排序比较两个 Employee(先按年龄比,年龄相同按姓名比),使用Lambda 作为参数传递。

        List<Employee> emps = Arrays.asList(
                    new Employee("张三", 18, 9999.99),
                    new Employee("李四", 38, 5555.99),
                    new Employee("王五", 50, 6666.66),
                    new Employee("赵六", 16, 3333.33),
                    new Employee("田七", 8, 7777.77)
            );
    
        @Test
        public void test1() {
            Collections.sort(emps,(e1,e2)->{
                if (e1.getAge()==e2.getAge()){
                    return e1.getName().compareTo(e2.getName());
                }else {
                    return Integer.compare(e1.getAge(),e2.getAge());
                } 
            });
            for (Employee emp : emps) {
                System.out.println(emp);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    2.① 声明函数式接口,接口中声明抽象方法,public String getValue(String str);

    @FunctionalInterface
    public interface MyFunction {
        public String getValue(String str);
    }
    
    • 1
    • 2
    • 3
    • 4

    strHandler 用于处理字符串的处理

      //需求 用于处理字符串的处理
        public String strHandler(String str, MyFunction mf) {
            return mf.getValue(str);
        }
    
    • 1
    • 2
    • 3
    • 4

    ② 声明类TestLambda ,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值。

      String s = strHandler("abcdef", str -> str.toUpperCase());
      System.out.println(s);
    
    • 1
    • 2

    ③ 再将一个字符串的第2个和第4个索引位置进行截取子串。

            String str = strHandler("\t\t\t\t java初学者", s1 -> s1.substring(2, 4));
            System.out.println(str);
    
    • 1
    • 2

    3.① 声明一个带两个泛型的函数式接口,泛型类型为T为参数,R为返回值。
    ② 接口中声明对应抽象方法

    @FunctionalInterface
    public interface MyFunction2<T,R> {
        public R getValue(T t1,T t2);
    }
    
    • 1
    • 2
    • 3
    • 4

    对于两个Long型数据进行处理

     //对于两个Long型数据进行处理
        public void op(Long l1, Long l2, MyFunction2<Long, Long> mf) {
            System.out.println(mf.getValue(l1, l2));
        }
    
    • 1
    • 2
    • 3
    • 4

    ③ 在TestLambda 类中声明方法,使用接口作为参数,计算两个long型参数的和。
    ④ 再计算两个 long型参数的乘积。

       @Test
        public void test3() {
            op(100L, 200L, (x, y) -> x + y);
            op(100L, 200L, (x, y) -> x * y);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    感谢参与:

    https://www.bilibili.com/video/BV1ut411g7E9?p=5

  • 相关阅读:
    pdf转cad怎么弄?教你这几种快速转换cad的方法
    Vue教学19:Element UI组件深入探索,构建精致的Vue应用界面
    linux shell求和计算脚本
    redux-获取导航标题案例(+react-intl 国际化)
    【three.js】结合vue进行开发第一个3d页面
    Socket编程实现简易聊天室
    Retrofit项目 - Android和Java的类型安全的HTTP客户端
    学习尚硅谷HTML+CSS总结
    【校招VIP】去年招770人,今年竟然只招50人??24届秋招真的好难。。。
    kubernetes使用(1.25)
  • 原文地址:https://blog.csdn.net/weixin_46665411/article/details/126304883