Java - Lambda Method References

Introduction

A method reference is shorthand to create a lambda expression using an existing method.

If a lambda expression contains a body that is an expression using a method call, you can use a method reference as lambda expression.

Method Reference is a shorthand for writing a lambda expression using an existing method.

Syntax

The general syntax for a method reference is

<Qualifier>::<MethodName>
  • <Qualifier> depends on the type of the method reference.
  • Two consecutive colons act as a separator.
  • <MethodName> is the name of the method.

For example, String::length, String is the qualifier and length is the method name.

A method reference is called later when its target type is called.

Example

Consider the following code:

ToIntFunction<String> lengthFunction = str -> str.length();
String name = "abcde";
int len = lengthFunction.applyAsInt(name);
System.out.println("Name = " + name + ", length = " + len);

The code uses a lambda expression to define an anonymous function that takes a String as an argument and returns its length.

The body of the lambda expression calls the length() method of the String class.

You can rewrite the lambda expression using a method reference to the length() method of the String class, as shown:


ToIntFunction<String> lengthFunction = String::length;
String name = "abcde";
int len = lengthFunction.applyAsInt(name);
System.out.println("Name = " + name + ", length = " + len);

If the method is an overloaded method, the compiler will choose the most specific method based on the context.

Types of Method References

The following table lists the types of method references.

Syntax
Description
TypeName::staticMethod
A method reference to a static method of a class, an interface, or an enum
objectRef::instanceMethod
A method reference to an instance method of the specified object
ClassName::instanceMethod

A method reference to an instance method of an object of the
specified class
TypeName.super::instanceMethod

A method reference to an instance method of the supertype of a
particular object
ClassName::new
A constructor reference to the constructor of the specified class
ArrayTypeName::new

An array constructor reference to the constructor of the specified
array type