0

下面显示的是一些使用 Java Streams 的示例代码。我的问题特别涉及Interface Function<T,R>which 接受 type 的输入T并返回 type 的东西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)

我们传递给的方法引用groupingsByDish::getCalories

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

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

请帮助消除我的困惑。

4

1 回答 1

5

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

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

于 2019-10-19T23:31:52.883 回答