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 Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.