What are method references, and how are they useful?

Solution:

Method references were introduced in Java 8 and allow constructors and methods (static or otherwise) to be used as lambdas. They allow one to discard the boilerplate of a lambda when the method reference matches an expected signature.

For example, suppose we have a service that must be stopped by a shutdown hook. Before Java 8, we would have code like this:

        final SomeBusyService service = new SomeBusyService();
        service.start();

        onShutdown(new Runnable() {
            @Override
            public void run() {
                service.stop();
            }
        });

With lambdas, this can be cut down considerably:

        onShutdown(() -> service.stop());

However, stop matches the signature of Runnable.run (void return type, no parameters), and so we can introduce a method reference to the stop method of that specific SomeBusyService instance:

        onShutdown(service::stop);

This is terse (as opposed to verbose code) and clearly communicates what is going on.

Method references don’t need to be tied to a specific instance, either; one can also use a method reference to an arbitrary object, which is useful in Stream operations. For example, suppose we have a Person class and want just the lowercase names of a collection of people:

        List<Person> people = ...

        List<String> names = people.stream()
                .map(Person::getName)
                .map(String::toLowerCase)
                .collect(toList());

A complex lambda can also be pushed into a static or instance method and then used via a method reference instead. This makes the code more reusable and testable than if it were “trapped” in the lambda.

So we can see that method references are mainly used to improve code organization, clarity and terseness.

0 answers