DEV Community

Jerome Ryan Villamor
Jerome Ryan Villamor

Posted on

Method Reference in Lambda

Method reference is a good way to reduce the noise inside our Java streams.

Say that we have a list of names, and we want to map each of them to full name. We can achieve that by using the code below:

public void example() {
    List <String> names = Arrays.asList("Jerome", "Steve", "Cathy", "Lara");

    names.stream()
        .map((String name) -> {
            User user = repository.getUser(name);
            String fullname = user.firstname + " " + user.lastname;
            return fullname;
        })
        .forEach((String name) -> System.out.println(name));
}
Enter fullscreen mode Exit fullscreen mode

Streams are not good for readability if your lambda methods contain many lines of codes. I prefer to have a rule of thumb that if it's 3 or more lines then we need to extract the code to its dedicated method.

public String getFullname(String name) {
    User user = repository.getUser(name);
    String fullName = user.firstname + " " + user.lastname;
    return fullname;
}
Enter fullscreen mode Exit fullscreen mode

Then use method reference to make our stream more concise and shorter.

public void example() {
    List <String> names = Arrays.asList("Jerome", "Steve", "Cathy", "Lara");

    names.stream()
        .map(this::getFullname)
        .forEach((String name) - > System.out.println(name));
}
Enter fullscreen mode Exit fullscreen mode

Note that a properly name method will make a difference. A code map(this::getFullname) can read as an English sentence. That's a sign of a cleaner and better code.

Top comments (0)