Lambda構造函數引用

  1. 缺省構造函數

package com.qingke.chapter2;

public class Apple {
    private String color;

    private int weight;

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
}

沒有構造函數,或者說只有缺省構造函數,則構造函數引用爲

 pool = Apple::new;
Apple a1 = ;
System..println(a1.getWeight());


2. 有一個參數的構造器

package com.qingke.chapter2;

public class Apple {
    private String color;

    private int weight;

  

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
}

構造函數只有一個入參,則構造函數引用爲:

 = Apple::new;
Apple a1 =;
System..println(a1.getColor());


3. 有多個參數的構造函數

package com.qingke.chapter2;

public class Apple {
    private String color;

    private int weight;

   

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
}

構造函數有兩個入參,請注意入參類型的順序,則構造函數引用爲:

= Apple::new;
Apple a = ;
System..println(a.getColor() + " " + a.getWeight());


請看下面代碼 (學着學着,有時候感覺也蠻有意思):

package com.qingke.chapter2;

public class Apple {
    private String color;

    private int weight;

    

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
}


定義一個map方法,將List中的數字傳遞給Apple的構造函數,得到一個具有不同重量蘋果的List

public static List<Apple> map(List<Integer> list, Function<Integer, Apple> f){

    List<Apple> result = new ArrayList<>();

    for(Integer element : list){

         result.add(f.apply(element));

    }

    return result;

}

下面調用,將構造函數引用傳遞給map方法:

List<Integer> weights = Arrays.(39, 38, 89, 101, 203);
List<Apple> apples = (weights, );


不將構造函數實例化卻能夠引用它,這個功能有一些有趣的應用:例如,你可以使用Map將構造函數映射到字符串值,此時你可以通過giveMeFruit(),給它一個String和一個Integer,它就可以創建出不同重量的各種水果:

static Map<String, Function<Integer, Fruit>> map = new HashMap<>();

static{

    map.put("apple", Apple::new);

    map.put("orange", Orange::new);

    ......

}


public static Fruit giveMeFruit(String fruit,  Integer){

     return map.get(fruit.toLowerCase()) // 得到一個Function<Integer, Fruit>

                .apply(weight); // 用Integer類型的weight參數調用Function的apply()方法將提供所要求的Fruit

}


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