java 8方法引用后面的场景

时间:2017-02-12 18:12:11

标签: java collections java-8 method-reference

我的问题是lambda,方法引用都是关于功能接口的。他们只是提供它们的实现。

现在当我写道:

class Apple{
private int weight;
private String color;

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;
}}

如果我写:

            Function<Apple, Integer> getWeight = Apple::getWeight;

        appleList.stream().map(Apple::getColor).collect(toList());

它是如何实际工作我的getter没有采取Apple的任何参数?因为根据功能功能界面

@FunctionalInterface
public interface Function<T, R> {
R apply(T t);}

它需要一个参数并返回一些东西,它应该真的有效 当吸气器像:

public int getWeight(Apple a) {
    return a.weight;
}

我提前感谢我有点困惑

2 个答案:

答案 0 :(得分:3)

这样的Function<Apple, Integer>不应与Apple的实例混淆。

还记得学校的功能吗? 你必须从域中获取一个元素(这里是来自Apple s的苹果),它将与codomain中的一个相应元素匹配(这里是Integer s的整数)。 Function本身并未分配给任何特定的苹果。

你可以这样使用它:

List<Apple> apples = new ArrayList<Apple>();
apples.add(new Apple(120, "red"));
apples.add(new Apple(150, "green"));
apples.add(new Apple(150, "yellow"));
List<String> colors = apples.stream()
                            .map(Apple::getColor)
                            .collect(Collectors.toList());
System.out.println(colors);

Apple::getColor相当于Function<Apple, String>,它返回每个苹果的颜色:

Function<Apple, Integer> getColor = new Function<Apple, Integer>() {
    @Override
    public Integer apply(Apple apple) {
        return apple.getColor();
    }
};

此外

List<String> colors = apples.stream()
                            .map(Apple::getColor)
                            .collect(Collectors.toList());

相当于:

List<String> colors = apples.stream()
                            .map(apple -> apple.getColor())
                            .collect(Collectors.toList());

答案 1 :(得分:3)

这在教程Method reference中清楚地记录为对特定类型的任意对象的实例方法的引用。由于对象具有引用方法类型的类型,因此该对象将是将在其上调用该方法的对象。意味着:

map( Apple::getColor )

相当于:

map( a -> a.getColor() )