|
|
Method References
Author: Venkata Sudhakar
Method references are a shorthand notation of a lambda expression that calls a method. They make code cleaner and more readable when a lambda expression simply calls an existing method. Types of Method References: 1. Static method: ClassName::staticMethod 2. Instance method of a particular object: object::instanceMethod 3. Instance method of an arbitrary object: ClassName::instanceMethod 4. Constructor reference: ClassName::new The below example shows all four types of method references in Java 8.
It gives the following output,
Doubled (static method ref):
2
4
6
8
10
Greetings:
Hello, Alice
Hello, Bob
Hello, Charlie
Uppercase (arbitrary object method ref):
ALICE
BOB
CHARLIE
Person objects (constructor ref):
Alice
Bob
Charlie
Print via method ref:
Alice
Bob
Charlie
When to use Method References vs Lambda: Use method references when the lambda body simply calls a single existing method. They are more concise and improve readability. Use lambdas when you need additional logic or transformations around the method call.
|
|