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

一、方法引用

注意:

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);
    }
原文地址:https://www.cnblogs.com/wangxue1314/p/12764588.html