寻求对函数的深入理解<T,R>

Seeking in-depth understanding of Function<T,R>

下面显示的是一些使用 Java 流的示例代码。我的问题特别涉及 Interface Function<T,R>,它接受 T 类型的输入,return 接受 R 类型的输入。

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.groupingBy;

import java.util.List;
import java.util.Map;

public class Dish {

  private final String name;
  private final boolean vegetarian;
  private final String calories;

  public Dish(String name, boolean vegetarian, String calories) {
    this.name = name;
    this.vegetarian = vegetarian;
    this.calories = calories;
  }

  public String getName() {
    return name;
  }

  public boolean isVegetarian() {
    return vegetarian;
  }

  public String getCalories() {
    return calories;
  }

  @Override
  public String toString() {
    return name;
  }

  public static final List<Dish> menu = asList(
      new Dish("pork", false, "GE 600"),
      new Dish("beef", false, "GE 600"),
      new Dish("chicken", false, "300-600"),
      new Dish("french fries", true, "300-600"),
      new Dish("rice", true, "LE 300"),
      new Dish("season fruit", true, "LE 300"),
      new Dish("pizza", true, "300-600"),
      new Dish("prawns", false, "300-600"),
      new Dish("salmon", false, "300-600")
  );

  public static void main(String[] args) {
        Map<String, List<Dish>> dishByCalories = menu.stream()
                .collect(groupingBy(Dish::getCalories));
        System.out.println(dishByCalories);
  }
}

显然 groupingBy(Dish::getCalories) 满足 collect 的预期方法签名要求(即 Collector<? super T,A,R> collector

现在 groupingsBy,其签名要求如下:
static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)

我们传递给 groupingsBy 的方法引用是 Dish::getCalories

显然 Dish::getCalories 满足 Function<? super T,? extends K> 的签名要求(即它应该接受 T 的某个超类的输入和 return K 的某个子类的结果)。

但是,getCalories 方法 不接受任何参数,它 return 是一个字符串。

请帮我解惑。

getCalories 是一个 实例 方法,因此它接受隐式 this 参数。

Dish::getCalories 等同于 lambda (Dish dish) -> dish.getCalories(),这使其成为 Function<Dish, String>.

的实现