Method References in Java
Introduction#
Method references in Java are a shorthand notation for lambda expressions that refer to existing methods. They improve readability and make the code more concise. Instead of writing a full lambda expression, we can directly refer to a method using ::
(double colon) operator.
In this blog, we will cover:
- What are Method References?
- 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
- Reference to a Constructor
- Examples for Each Type
What are Method References?#
Method references allow us to pass a method as an argument to another method, making the code more readable and easier to understand. Instead of writing a full lambda expression, we can use a method reference when the lambda body only calls a single existing method.
Syntax:#
Let's explore the different types of method references in detail.
1. Reference to a Static Method#
This type of method reference is used when we want to refer to a static method of a class.
Example:#
When to Use: If a lambda expression directly calls a static method, use a method reference instead.
2. Reference to an Instance Method of a Particular Object#
If we have an object and want to call one of its instance methods using a functional interface, we can use this method reference.
Example:#
When to Use: When you have an existing object and need to call its method via a functional interface.
3. Reference to an Instance Method of an Arbitrary Object#
This is useful when working with streams or collections. It allows us to refer to an instance method of an unknown object (arbitrary instance of a class).
Example:#
When to Use: When iterating over a collection and applying the same instance method to all elements.
4. Reference to a Constructor#
Constructor references allow us to create new instances without using the new
keyword explicitly in a lambda expression.
Example:#
When to Use: When we need to create new objects using functional interfaces like Supplier<T>
.
Conclusion#
In this blog, we explored Method References in Java and their different types:
- Reference to a Static Method (ClassName::methodName)
- Reference to an Instance Method of a Particular Object (objectReference::methodName)
- Reference to an Instance Method of an Arbitrary Object (ClassName::methodName)
- Reference to a Constructor (ClassName::new)
Method references simplify lambda expressions and make code more readable. They are particularly useful when working with streams and functional interfaces. By using method references, we can write cleaner, more efficient Java code.