Java 8 mapToInt and toIntFunction examples

Remember a method reference is just a shortcut for a lambda. So an instance method reference is a lambda that calls that method on the argument. The type of the argument is the class given in the method reference. It helps to "unwrap" it.

MyPerson::getAge

Unwrap to a lambda:

(MyPerson p) -> p.getAge()

Unwrap to an anonymous class:

new ToIntFunction<MyPerson>() {
    @Override
    public int applyAsInt(MyPerson p) {
        return p.getAge();
    }
}

With a static method reference, the signature must match exactly, that is, the static method takes a T and returns an int. With an instance method reference, the parameter T of the lambda is the object the method gets called on.


As far as I know MyPerson::getAge is like a pointer to MyPersons getAge() method, which returns an int. So value.getAge() gets invoked in int applyAsInt(MyPerson value);. In other words: You just tell the stream, that it should use getAge()s return value from it's current MyPerson iteration variable to construct another collection an IntStream.