幕后的Java 8方法引用

标签 java collections java-8 method-reference

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

现在当我写:

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

它实际上是如何工作的,我的 setter/getter 没有采用 Apple 的任何参数?因为根据function功能接口(interface)

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

它需要一个参数并返回一些东西,它应该可以正常工作 当 setter/getter 是这样的:

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

我有点困惑提前谢谢

最佳答案

这样一个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());

关于幕后的Java 8方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42191321/

相关文章:

playframework - Play 2.4 - 在 Eager 单例模块中使用 Ebean

java - scala 中的 cogroup 两个 RDD

Java:Set接口(interface)和Collection接口(interface)的区别

java - weblogic 12.1.3 config.sh 显示错误

java - JPA:如何设置 MySQL session 变量?

java - Java编译器如何转换包含自定义类的Collections?

Java 8 列表到 map 的转换

java - 使用 java 8 计算列表中对象的属性

java - 下拉菜单未按预期工作

java - 插入排序和哨兵