Lamda表达式学习笔记二

Lamda表达式学习笔记二

 

lamda表达式----方法引用

上一篇讲到Lamda体就是对函数式接口方法的实现 ,在方法体中咱们可能会引用其余方法实现逻辑,因此在lamda体中咱们能够直接引用器方法app

I 对象::实例方法名

/**
     * 对象::实例方法名
     */
    @Test
    public void test6() {
        Consumer<String> consumer = (x) -> System.out.println(x);
        consumer.accept("->");
        Consumer<String> consumer1 = System.out::println;
        consumer1.accept("::");
    }

 

结果:

II 类名::静态方法名

 /**
     * 类名::静态方法名
     */
    @Test
    public void test7() {
        Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
        
        Comparator<Integer> comparator1 = Integer::compare;
    }

 

 III 类名::实例方法名

 

/**
     * 类名::实例方法名
     */
    public void test8() {
        BiFunction<String, String, Boolean> biFunction = (x, y) -> x.equals(y);
        BiFunction<String, String, Boolean> biFunction1 = String::equals;
    }

 

 

 结论:一、引用的方法与函数式接口中抽象方法的入参出参保持一致ide

    二、使用第三种lamda表达式时,只有入参只能为2个且参数列表中第一个参数是类的实例,参数列表中第二个参数是实例方法的参数时才能够用函数

 I,II仅需知足结论1,III须要同时知足结论1和结论2学习

 

Lamda表达式----构造器引用

/**
     * 类名::构造器
     */
    @Test
    public void test9() {
        Supplier<Student> studentSupplier = Student::new;
        System.out.println("Supplier:" + studentSupplier.get());
        Function<String, Student> function = Student::new;
        System.out.println("Function:" + function.apply("李四"));
        BiFunction<Integer, Double, Student> biFunction = Student::new;
        System.out.println("BiFunction:" + biFunction.apply(10, 150.0));

    }

 

结果:spa

Supplier:Student{name='null', age=null, hight=null}
Function:Student{name='李四', age=null, hight=null}
BiFunction:Student{name='null', age=10, hight=150.0}

Process finished with exit code 0

 

构造器遵循结论1(引用的方法与函数式接口中抽象方法的入参出参保持一致),是根据构造方法的参数数量来匹配构造方法code

 

我的学习,侵删对象

 

参考:https://www.bilibili.com/video/av62117143blog