Introduction
Java Method Reference is a feature introduced in Java 8 that provides a concise and readable way to refer to existing methods without invoking them directly. It works closely with Lambda Expressions, Functional Interfaces, and the Stream API, making Java code cleaner, shorter, and easier to understand.
Before Java 8, developers often used anonymous inner classes to implement interfaces. Java 8 introduced Lambda Expressions to reduce boilerplate code. However, in many cases, a lambda expression simply calls an existing method. Instead of writing a lambda, Java allows you to reference that method directly using a Method Reference.
For example, consider the following lambda expression:
List names = Arrays.asList("Java", "Python", "C++");
names.forEach(name -> System.out.println(name));
The lambda simply calls System.out.println(). Using a Method Reference, the same code becomes:
List names = Arrays.asList("Java", "Python", "C++");
names.forEach(System.out::println);
The Method Reference version is shorter, easier to read, and clearly expresses the intent of the code.
Method References are widely used with the Stream API, Collections Framework, Comparator, Threads, Event Handling, and Functional Interfaces. They improve code readability by eliminating unnecessary lambda expressions when an existing method already performs the required operation.
In this tutorial, you’ll learn everything about Java Method References, including syntax, types, examples, real-life applications, advantages, limitations, common mistakes, best practices, and interview questions.
What is a Java Method Reference?
A Method Reference is a shorthand notation for a lambda expression that directly calls an existing method.
Instead of writing:
x -> x.toUpperCase()
You can write:
String::toUpperCase
A Method Reference does not execute the method immediately. It simply provides a reference to the method, which is invoked later when required by a Functional Interface.
Why Do We Need Method References?
Lambda expressions make Java code shorter, but sometimes they simply call another method without adding any additional logic.
Example using Lambda:
List list =
Arrays.asList("Java", "Python", "C++");
list.forEach(item -> System.out.println(item));
Using Method Reference:
list.forEach(System.out::println);
The Method Reference version is more readable and removes unnecessary code.
Features of Method References
Some important features are:
- Introduced in Java 8
- Reduces boilerplate code
- Improves code readability
- Works with Functional Interfaces
- Supports Lambda Expressions
- Integrates with Stream API
- Can reference constructors
- Can reference static methods
- Can reference instance methods
- Encourages functional programming
Syntax
The general syntax is:
ClassName::methodName
or
objectReference::methodName
or
ClassName::new
The :: operator is called the Method Reference Operator.
Types of Method References
Java supports four types of Method References:
- Reference to a Static Method
- Reference to an Instance Method of a Particular Object
- Reference to an Instance Method of an Arbitrary Object of a Particular Type
- Reference to a Constructor
Let’s understand each one with examples.
1. Reference to a Static Method
Syntax:
ClassName::staticMethod
Example:
import java.util.function.Function;
public class Main {
public static int square(int number) {
return number * number;
}
public static void main(String[] args) {
Function function = Main::square;
System.out.println(function.apply(5));
}
}
Output
Here, Main::square refers to the static method square().
2. Reference to an Instance Method of a Particular Object
Syntax:
objectReference::instanceMethod
Example:
class Printer {
public void print(String message) {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
Printer printer = new Printer();
Consumer consumer = printer::print;
consumer.accept("Welcome to Java");
}
}
Output
The Method Reference points to the print() method of a specific object.
3. Reference to an Instance Method of an Arbitrary Object
Syntax:
ClassName::instanceMethod
Example:
import java.util.*;
public class Main {
public static void main(String[] args) {
List names =
Arrays.asList("Java", "Python", "C++");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output
PYTHON
C++
Here, String::toUpperCase is applied to each element in the stream.
4. Reference to a Constructor
Syntax:
ClassName::new
Example:
interface EmployeeFactory {
Employee create();
}
class Employee {
Employee() {
System.out.println("Employee Created");
}
}
public class Main {
public static void main(String[] args) {
EmployeeFactory factory = Employee::new;
factory.create();
}
}
Output
The constructor is called using a Method Reference.
Method Reference vs Lambda Expression
Lambda Expression:
numbers.forEach(number -> System.out.println(number));
Method Reference:
numbers.forEach(System.out::println);
Both produce the same output, but the Method Reference is cleaner when the lambda only calls an existing method.
Example 1: Printing List Elements
import java.util.*;
public class Main {
public static void main(String[] args) {
List languages =
Arrays.asList("Java", "Python", "C++");
languages.forEach(System.out::println);
}
}
Output
PYTHON
C++
Example 2: Sorting Using Method Reference
import java.util.*;
public class Main {
public static void main(String[] args) {
List names =
Arrays.asList("Rahul", "Amit", "Neha");
Collections.sort(names, String::compareTo);
System.out.println(names);
}
}
Output
Note: If the input list is [“Rahul”, “Amit”, “Neha”], the actual output will be:
Example 3: Stream API with Method Reference
import java.util.*;
public class Main {
public static void main(String[] args) {
List numbers =
Arrays.asList(10, 20, 30);
numbers.stream()
.map(String::valueOf)
.forEach(System.out::println);
}
}
Output
20
30
Example 4: Using Constructor Reference
interface CarFactory {
Car create();
}
class Car {
Car() {
System.out.println("Car Created");
}
}
public class Main {
public static void main(String[] args) {
CarFactory factory = Car::new;
factory.create();
}
}
Output
Method Reference with Functional Interfaces
Method References work only with Functional Interfaces.
Example:
@FunctionalInterface
interface Greeting {
void display();
}
public class Main {
public static void message() {
System.out.println("Welcome");
}
public static void main(String[] args) {
Greeting greeting = Main::message;
greeting.display();
}
}
Output
Real-life Example
Imagine an Employee Management System where employee names need to be printed.
Using Lambda:
employees.forEach(employee ->
System.out.println(employee.getName()));
Using Method Reference:
employees.stream()
.map(Employee::getName)
.forEach(System.out::println);
Other real-world applications include:
- Sorting collections
- Data filtering
- Stream processing
- Event handling
- Thread creation
- Database record processing
- Report generation
- REST API development
Advantages of Method References
- Reduces boilerplate code
- Improves readability
- Cleaner than simple lambda expressions
- Encourages code reuse
- Easy integration with Stream API
- Supports constructor references
- Simplifies collection processing
- Makes functional programming more expressive
Limitations of Method References
- Works only when an existing method matches the required functional interface signature.
- Cannot replace lambdas that contain additional business logic.
- May reduce readability if overused in complex codebases.
- Requires familiarity with functional programming concepts.
Common Mistakes
1. Using Method Reference with a Non-Functional Interface
Incorrect:
interface Demo {
void method1();
void method2();
}
Method References require a Functional Interface containing exactly one abstract method.
2. Using Method Reference When Additional Logic Is Needed
Incorrect:
list.forEach(System.out::println);
If you need extra processing:
list.forEach(item -> {
System.out.println("Item: " + item);
});
A Method Reference cannot replace this lambda because additional logic is present.
3. Incorrect Method Signature
The referenced method must match the Functional Interface.
Incorrect:
Function function = String::substring;
The method signature does not match the Function<String, Integer> interface.
4. Forgetting the :: Operator
Incorrect:
System.out.println
Correct:
System.out::println
5. Overusing Method References
Method References improve readability only when they are simple. If the code becomes difficult to understand, use a lambda expression instead.
Best Practices
- Use Method References when they make the code shorter and clearer.
- Prefer Method References over simple lambda expressions that only call an existing method.
- Continue using lambda expressions when additional processing is required.
- Use constructor references for object creation with Functional Interfaces.
- Combine Method References with the Stream API for cleaner collection processing.
- Ensure the referenced method matches the Functional Interface’s method signature.
Time Complexity
A Method Reference itself does not affect time complexity. The complexity depends on the referenced method.
| Operation | Time Complexity |
|---|---|
| Method Reference Invocation | O(1) |
| forEach() | O(n) |
| map() | O(n) |
| filter() | O(n) |
| sorted() | O(n) |
Conclusion
The Java Method Reference feature is a powerful enhancement introduced in Java 8 that makes code more concise, readable, and maintainable. By replacing simple Lambda Expressions with references to existing methods or constructors, Method References reduce boilerplate code and improve clarity. They integrate seamlessly with Functional Interfaces, Lambda Expressions, and the Stream API, making them an essential part of modern Java development.