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

}


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