Skip to content

What Are Method References?

In this lesson, you will learn about the method reference operator, its usage, and an example code with a detailed explanation.

Gopi Gorantala
Gopi Gorantala
2 min read

Table of Contents

Introduction

Method references provide a shorthand syntax for lambda expressions that call a single method.

Method reference is a wonderful feature introduced in Java 8. Apart from taking advantage of functional programming, one of the biggest advantages of using a Method Reference is it minimizes the number of lines of code even more than lambda expressions.

What is a Method reference?

Method reference operator :: is used to refer to the methods of functional interface.

Lambda expressions are used to create anonymous methods. A method reference is a compact way of writing a lambda expression that calls a specific method.

Most of the time, we do some operations inside the lambda expression. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, referring to the existing method by name is often clearer.

So, whenever you use a lambda expression to refer to a method, you can do the same using a method reference. In other words, replace the lambda expression with a method reference, which works!

Method references allow you to do this. They are compact each-to-read lambda expressions for methods that already have a name.

Method references are a special type of lambda expression. They're often used to create simple lambda expressions by referring to existing methods.

String Operations

Consider we have some fruits which we added to a collection object. We want each to transform or mutate its state using method reference. In short, .map method of Streams API replaces the existing values with the condition provided inside it.

import java.util.Arrays;
import java.util.List;

public class StringOperations {
  public static void main(String[] args) {
    List<String> fruits = Arrays.asList("Apple", "Banana", "guava", "grapes");
    helper(fruits);
  }

  // String operation using method reference
  private static void helper(List<String> fruits) {
    fruits // collection of fruits
        .stream() // stream of fruits
        // mapping/transforming each stream value using method reference
        .map(String::toUpperCase)
        // printing them using method reference (shorthand syntax)
        .forEach(System.out::println);
  }
}

Explanation

When you run the program, the compiler starts from the main method, scanning through each line.

In line 6, we have a list of fruits stored in a collection.

Line 7 calls a method, and the compiler jumps to line 11.

Line 13, we converted the collection of fruits into the stream of fruits by calling/chaining fruits object with .stream().

We chained an intermediate operation .map which transforms the given stream and replaces them with the condition passed as Predicate, in this case, a method reference String::toUpperCase.

Line 17 contains .forEach method that iterates through the stream of fruits and prints them line by line using a method reference System.out::println.

So, why not Lambdas?

We could have used lambda expression inside the intermediate operation .map(...) and terminal operation forEach like below.

fruits.stream()
  .map(s -> s.toUpperCase())
  .forEach(fruit -> System.out.println(fruit));

But, method reference syntaxes are clean and simple. The above lambda expressions are refactored with method reference as follows.

fruits.stream()
  .map(String::toUpperCase)
  .forEach(fruit -> System.out.println(fruit));

Lambda Expressions to Method References

Here are some examples of replacing the lambda expressions using method references.

Lambda Expression Method Reference
s -> s.toLowerCase() String::toLowerCase
s.toLowerCase() String::toLowerCase
(a, b) -> a.compareTo(b) For Integers, it will be Integer::compareTo
and for strings it is String::compareTo
(a, b) -> Person.compareByAge(a, b) Person::compareByAge

This is a refresher on method references. You will learn in more detail in the next lessons.

In the next lessons, we learn about different kinds of method references, their uses, example code snippets etc.

Java

Gopi Gorantala Twitter

Gopi is a highly experienced Full Stack developer with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

How To Write Lambda Expressions

This lesson introduces the basic lambda expression structure with tips to write efficient code.

Members Public

What Are Lambda Expressions?

This is an introductory lesson on lambda expressions. You will learn about the lambda operator, expression, syntaxes and more!

Members Public

Power Of Two (Exercise Problem)

This is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!