VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • java入门之Lamda表达式学习笔记二

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

上一篇讲到Lamda体就是对函数式接口方法的实现 ,在方法体中我们可能会引用其他方法实现逻辑,所以在lamda体中我们可以直接引用器方法

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;
    }
复制代码

 

 

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

    2、使用第三种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));

    }
复制代码

 

结果:

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(引用的方法与函数式接口中抽象方法的入参出参保持一致),是根据构造方法的参数数量来匹配构造方法

 

个人学习,侵删

 

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

相关教程