【问题标题】:java 8 method reference behind the scenejava 8 幕后方法参考
【发布时间】:2017-02-12 18:12:11
【问题描述】:

我的问题是 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;
}

我有点困惑提前谢谢

【问题讨论】:

    标签: java collections java-8 method-reference


    【解决方案1】:

    不要将这样的Function&lt;Apple, Integer&gt;Apple 的实例混淆。

    还记得学校的功能吗?
    您必须从域中获取一个元素(这里是来自 Apples 的苹果),它将与来自 codomain 的一个对应元素(这里是来自 Integers 的整数)完全匹配。 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&lt;Apple, String&gt;,它返回每个苹果的颜色:

    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());
    

    【讨论】:

      【解决方案2】:

      这在教程Method reference 中明确记录为对特定类型的任意对象的实例方法的引用。由于对象具有引用方法类型的类型,因此该对象将是调用该方法的对象。意思是:

      map( Apple::getColor )
      

      相当于:

      map( a -> a.getColor() )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-19
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多