Lambda的更高級——方法引用,構造器引用,數組引用

前言——Lambda表達式的本質:作爲函數式接口的實例——省略部分代碼。

函數式接口:如果一個接口中,只聲明瞭一個抽象方法,則此接口就稱爲函數式接口。我們可以在一個接口上使用 @FunctionalInterface 註解,這樣做可以檢查它是否是一個函數式接口。

 

總的來說,Lambda是接口匿名內部類書寫的簡化版,方法引用、構造器引用、數組引用時Lambda的簡化版。

 

一、方法引用。

見上一篇文章

https://blog.csdn.net/ly_xiamu/article/details/106771969

方法引用——本質上就是Lambda表達式——具體使用的三種情況舉例

 



二、構造器引用。

*     格式爲     對象::new

*      和方法引用類似,函數式接口的抽象方法的形參列表和構造器的形參列表一致。
*      抽象方法的返回值類型即爲構造器所屬的類的類型,舉例如下

//構造器引用
    //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"));

    }

 


 三、數組引用

格式爲  type [] :: new

*     大家可以把數組看做是一個特殊的類,則寫法與構造器引用一致。如下:

	//數組引用
    //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));

    }

 

輔助閱讀:java8的新特性之一——Lambda的6種語法格式——舉例對比前後差異

https://blog.csdn.net/ly_xiamu/article/details/106770790

 

一個程序員的自我修養和成長…
這裏可以找到我,微信公衆號。
在這裏插入圖片描述

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章