这样的函数< Apple,Integer>不要与Apple的实例混淆.
还记得学校的功能吗?
你必须从域中获取一个元素(这里是来自苹果的苹果),它将与codomain中的一个相应元素匹配(这里是整数的整数).函数本身未分配给任何特定的苹果.
你可以这样使用它:
List apples = new ArrayList();
apples.add(new Apple(120, "red"));
apples.add(new Apple(150, "green"));
apples.add(new Apple(150, "yellow"));
List colors = apples.stream()
.map(Apple::getColor)
.collect(Collectors.toList());
System.out.println(colors);
Apple :: getColor相当于一个函数< Apple,String>,它返回每个苹果的颜色:
Function getColor = new Function() {
@Override
public Integer apply(Apple apple) {
return apple.getColor();
}
};
此外
List colors = apples.stream()
.map(Apple::getColor)
.collect(Collectors.toList());
相当于:
List colors = apples.stream()
.map(apple -> apple.getColor())
.collect(Collectors.toList());