zoukankan      html  css  js  c++  java
  • java 基本语法(十七)Lambda (四)构造器引用与数组引用

    1.构造器引用格式:
    类名::new

    2.构造器引用使用要求:
    和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。抽象方法的返回值类型即为构造器所属的类的类型

    3.构造器引用举例:

    复制代码

    //Supplier中的T get()
       //Employee的空参构造器:Employee()
       @Test
       public void test1(){
    
           Supplier<Employee> sup = new Supplier<Employee>() {
               @Override
               public Employee get() {
                   return new Employee();
               }
           };
           System.out.println("*******************");
    
           Supplier<Employee>  sup1 = () -> new Employee();
           System.out.println(sup1.get());
    
           System.out.println("*******************");
    
           Supplier<Employee>  sup2 = Employee :: new;
           System.out.println(sup2.get());
       }
    
    //Function中的R apply(T t)
       @Test
       public void test2(){
           Function<Integer,Employee> func1 = id -> new Employee(id);
           Employee employee = func1.apply(1001);
           System.out.println(employee);
    
           System.out.println("*******************");
    
           Function<Integer,Employee> func2 = Employee :: new;
           Employee employee1 = func2.apply(1002);
           System.out.println(employee1);
    
       }
    
    //BiFunction中的R apply(T t,U u)
       @Test
       public void test3(){
           BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id,name);
           System.out.println(func1.apply(1001,"Tom"));
    
           System.out.println("*******************");
    
           BiFunction<Integer,String,Employee> func2 = Employee :: new;
           System.out.println(func2.apply(1002,"Tom"));
    
       }

    复制代码

    4.数组引用格式:
    数组类型[] :: new

    5.数组引用举例:

    复制代码

    //Function中的R apply(T t)
    @Test
    public void test4(){
        Function<Integer,String[]> func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(Arrays.toString(arr1));
    
        System.out.println("*******************");
    
        Function<Integer,String[]> func2 = String[] :: new;
        String[] arr2 = func2.apply(10);
        System.out.println(Arrays.toString(arr2));
    
    }
  • 相关阅读:
    readonly
    怎么查看ubuntu是32bit还是64bit的?
    array_diff使用注意
    PhpStorm 快速查找文件 `Ctrl`+`Shift`+`N`
    discuz安装,uc_server目录下乱码问题:
    vim,删除所有
    查看文件大小
    代码调试小结(一)
    Ansible 远程执行脚本
    Ansible 拷贝文件或目录
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13308969.html
Copyright © 2011-2022 走看看