我的问题是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());它是如何工作的,我的吸气器没有任何参数的苹果?因为根据功能功能接口
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);}它需要一个参数并返回一些内容,当getter类似于:
public int getWeight(Apple a) {
return a.weight;
}我有点困惑,先谢谢
发布于 2017-02-12 18:38:05
这样的Function<Apple, Integer>不应与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<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());发布于 2017-02-12 20:59:10
教程方法参考中清楚地说明了这一点,作为对特定类型的任意对象的实例方法的引用。由于该对象具有引用方法类型的类型,那么该对象将是调用该方法的对象。意思是:
map( Apple::getColor )相当于:
map( a -> a.getColor() )https://stackoverflow.com/questions/42191321
复制相似问题