为什么编译器将方法引用转换为实现功能接口的对象?

时间:2017-04-13 13:26:14

标签: java-8 java-stream method-reference functional-interface

    // sum of Employee salaries with DoubleStream sum method
    System.out.printf(
        "%nSum of Employees' salaries (via sum method): %.2f%n",
        list.stream()
            .mapToDouble(Employee::getSalary)
            .sum());

    // calculate sum of Employee salaries with Stream reduce method
    System.out.printf(
        "Sum of Employees' salaries (via reduce method): %.2f%n",
        list.stream()
            .mapToDouble(Employee::getSalary)
            .reduce(0, (value1, value2) -> value1 + value2));

    // average of Employee salaries with DoubleStream average method
    System.out.printf("Average of Employees' salaries: %.2f%n",
        list.stream()
            .mapToDouble(Employee::getSalary)
            .average()
            .getAsDouble());

上面是代码的一部分,让我感到困惑的是我现在正在从一本书中学习哪些Streams。它解释了Stream方法mapToDouble将对象映射到double值并返回DoubleStream,因此我们将Employee个对象映射到他们的工资,以便计算{{1 }和sum

方法average接收实现功能接口mapToDouble的对象。此接口的ToDoubleFunction方法调用对象上的实例方法并返回applyAsDouble值。方法参考double将当前Employee::getSalary的工资作为Employee返回。然后编译器将此方法引用转换为实现功能接口double的对象。

我不明白为什么编译器需要将方法引用转换为对象?提前谢谢!

0 个答案:

没有答案