In the stream, I use mapToInt, in which I must pass a reference to a method with type ToIntFunction
the signature is simple
@FunctionalInterface
public interface ToIntFunction<T> {
int applyAsInt(T value);
}
This means that the method to which I can pass a reference to mapToInt must contain an input parameter. However, I manage to pass a getter that takes no incoming parameters and returns an int
myList.stream().mapToInt(Transaction::getValue).average().getAsDouble();
Here is the getter
public int getValue() {
return value;
}
Why is it possible to pass a reference to a getter to where the ToIntFunction type is expected where the applyAsInt method has an input parameter
In a method reference to an instance method, the receiver is treated as the first parameter.
So Transaction::getValue
is converted to the equivalent of (Transaction t) -> t.getValue()
.