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