🔍 What is a Method Reference in Java?
A method reference is a shorthand notation of a lambda expression to call a method directly. It makes your code more readable and concise, especially when you're simply forwarding parameters.
Introduced in Java 8, method references can be used anywhere a lambda expression is used—particularly with functional interfaces.
🧠 Functional Interface Example
Let’s define a simple functional interface called Converter
:
java
@FunctionalInterface
interface Converter {
String convert(String input);
}
🔧 Static Method Example
We’ll now create a utility class with a static method:
java
class StringUtils {
static String toUpperCase(String str) {
return str.toUpperCase();
}
}
✅ Lambda vs Method Reference
Here’s how you can use both a lambda expression and a method reference to convert a string to uppercase:
java
public class Main {
public static void main(String[] args) {
// Using lambda expression
Converter converterLambda = (input) -> StringUtils.toUpperCase(input);
System.out.println(converterLambda.convert("hello")); // Output: HELLO
// Using method reference
Converter converterMethodRef = StringUtils::toUpperCase;
System.out.println(converterMethodRef.convert("hello")); // Output: HELLO
}
}
🆚 Lambda Expression vs Method Reference
Lambda ExpressionMethod Reference(input) -> StringUtils.toUpperCase(input)StringUtils::toUpperCase
More flexibleMore conciseSlightly more verboseEasier to read
🧩 Other Types of Method References
Java 8 supports four types of method references:
- Static method reference:
ClassName::staticMethod
- Instance method of a particular object:
instance::instanceMethod
- Instance method of an arbitrary object of a particular type:
ClassName::instanceMethod
- Constructor reference:
ClassName::new
✅ Why Use Method References?
- Improves readability
- Reduces boilerplate code
- Works seamlessly with functional interfaces (like
Function
, Consumer
, Predicate
)
Conclusion:
Method references are a great way to make your Java 8 code cleaner and easier to understand. They're especially useful when you're working with streams, lambdas, and functional programming patterns. Think of them as an elegant shortcut to calling existing methods!