为什么我可以将 getter 引用传递给 stream().mapToInt(...)?

Why can I pass a getter reference to stream().mapToInt(...)?

在流中,我使用 mapToInt,其中我必须传递对类型为 ToIntFunction 的方法的引用

签名很简单

@FunctionalInterface
public interface ToIntFunction<T> {
    int applyAsInt(T value);
}

这意味着我可以向其传递对 mapToInt 的引用的方法必须包含一个输入参数。 但是,我设法传递了一个不带传入参数的 getter 和 returns 一个 int

myList.stream().mapToInt(Transaction::getValue).average().getAsDouble();

这是getter

public int getValue() {
return value;
}

为什么可以将对 getter 的引用传递到需要 ToIntFunction 类型的位置,其中 applyAsInt 方法具有输入参数

在实例方法的方法引用中,接收者被视为第一个参数。

因此 Transaction::getValue 转换为 (Transaction t) -> t.getValue() 的等价物。