首页 > 编程语言 > 详细

Lambda 方法引用 构造器引用 数组引用

时间:2020-04-24 00:31:14      阅读:81      评论:0      收藏:0      [点我收藏+]

一、方法引用

注意:

1、Lambda 体中调用方法的参数列表与返回值类型,
要与函数式接口中的抽象方法的函数列表和返回值保持一致!
2、若Lambda 参数列表中的第一个参数是实例方法的调用者,
而第二个参数是实例方法的参数时,可以使用ClassName::method

 

类::实例方法名

 @Test
    public void test4(){
        BiPredicate<String,String> bi=(x,y)->x.equals(y);

        BiPredicate<String,String> bi2=String::equals;
    }

 

类::静态方法名

 @Test
    public void test3(){
        Comparator<Integer>com=(x,y)->Integer.compare(x,y);

        Comparator<Integer> com2=Integer::compare;
    }

 

对象::实例方法名

@Test
    public void test2(){
        Employee employee = new Employee();
        Supplier<String> sp1 = ()->employee.getName();
        String s=sp1.get();
        System.out.println(s);

        Supplier<Integer> sp = employee::getAge;
        Integer integer=sp.get();
        System.out.println(integer);
    }

 

 

二:构造器引用

格式:ClassName::new

注意:

需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致!

 //构造器引用
    @Test
    public void test5(){
        Supplier<Employee> su=()->new Employee();

        Supplier<Employee> su2=Employee::new;
        Employee em =su2.get();
        System.out.println(em);
    }

 

三、数组引用

Type::new

@Test
    public void test7(){
        Function<Integer,String[]> fun=x ->new String[x];
        String[] str=fun.apply(3);
        System.out.println(str.length);
        Function<Integer,String[]> fun2=String[]::new;
        String[] str2=fun.apply(4);
        System.out.println(str2.length);
    }

 

Lambda 方法引用 构造器引用 数组引用

原文:https://www.cnblogs.com/wangxue1314/p/12764588.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!