A Guide to Method References in Java 8

Understanding Java enums
Reading Time: 2 minutes

In this blog, we will get to know about method references in Java, where and how to use them.

What are Method References?

Method References allow us to pass the name of a method where a functional interface is expected.

This brings us to another question.

What is a Functional Interface?

Functional Interfaces are single-method interfaces that encapsulate a single behaviour. For eg. Runnable which has a single method run(). The standard library contains many built-in functional interfaces that you can use inside the java.util.function package.

Following is the general syntax of a functional interface.

@FunctionalInterface
interface MyInterface{
  ReturnType methodName(FunctionParameters){
    FunctionBody
  }
}

Now that we know about Functional Interfaces too, it’s time to learn how to use method references.

How are Method References used?

As told previously, method references are used to pass the name of the method where a functional interface is expected. We use the following syntax to refer to a method on a particular instance of a class.

instanceReference::methodName

Note: The type signature of the referenced method and that of the method in the functional interface must match.

Let’s say the method that is to be passed is this.

public void printUser(User user){
  System.out.println(user.toString());
}

And the place where the above function is to be passed is something like this.

public void applyToUser(User user, Consumer<User> f){
  f.accept(user);
}

Here, the second parameter to the function is a Consumer interface which simply accepts the user object/instance. So we can pass the function printUser in place of the interface as an implementation.

We can do this by doing the following :

User bob = new User("Bob");
applyToUser(bob, this::printUser);

The output of the code above is as below. The string passed to the object, in this case, the name of the person is printed.

output: Bob

This is equivalent to providing a lambda in-place of the functional interface.
This is shown below.

applyToUser(bob, (User user) -> printUser(user));

In case the method is a static method, use the following syntax for method reference.

Classname::staticMethodName

I hope the above examples were helpful in understanding method references. These benefit us by preventing redundant code.

That’s it for this blog. Keep learning folks!!

References:

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
https://blog.knoldus.com/functional-interfaces-in-java8/


knoldus-advt-sticker