Method References
A method reference is a shorthand way of referring directly to an existing method, using it as if it were a lambda expression, without rewriting its logic again.
1. What is a Method Reference?
A method reference is a shorthand way of referring directly to an existing method, using it as if it were a lambda expression, without rewriting its logic again.
2. Why is it used?
When a lambda expression would simply call an existing method with no extra logic, a method reference makes the code shorter and clearer by directly pointing to that method instead.
3. Real-Life Example
Think of saying "just do what the manual says," pointing directly to an existing instruction manual, instead of rewriting all those instructions again yourself. A method reference "points to" existing method logic instead of duplicating it.
4. Syntax
javaClassName::methodName
5. Example Program
javaimport java.util.List; import java.util.Arrays; public class MethodReferenceDemo { public static void main(String[] args) { List<String> names = Arrays.asList("Aman", "Riya", "Karan"); names.forEach(System.out::println); } }
Output:
Aman
Riya
Karan6. Key Points to Remember
- Method references use the
::syntax between the class (or object) and the method name. - They work only in places where a matching lambda expression could also be used.
- Common forms include static method references, instance method references, and constructor references.