Advanced Java · Lesson 93 of 150
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.
01What 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.
02Why 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.
03Real-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.
04Syntax
javaClassName::methodName
05Example 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
Karan