Commit 762312f
committed
feat: demonstrate method references (static, instance, and predefined) in Java
WHAT was done:
- Created a functional interface `MyRefrences` with a single abstract method `display(String str)`.
- Implemented three variations of method references:
1. **Static method reference** → `MethodRefrences::reverse`
- Points to a static method that reverses a string using `StringBuffer.reverse()`.
2. **Instance method reference** → `MD::reverse1`
- Points to a non-static method of a specific object.
3. **Predefined method reference** → `System.out::println`
- Refers to Java’s built-in `println` method to directly print strings.
KEY LEARNINGS:
1. Method Reference Basics:
- Syntax: `ClassName::methodName` (static) or `object::methodName` (instance).
- They provide a shorthand for writing simple lambda expressions.
- Example: `str -> System.out.println(str)` ≡ `System.out::println`.
2. Types of Method References:
- Static method reference → `ClassName::staticMethod`.
- Instance method reference (specific object) → `object::instanceMethod`.
- Instance method reference (arbitrary object) → `ClassName::instanceMethod`.
- Constructor reference → `ClassName::new`.
3. Advantage:
- Improves readability by eliminating boilerplate.
- Useful when lambda just calls an existing method.
EXAMPLE EQUIVALENCE:
- Lambda: `(s) -> System.out.println(s)`
- Method reference: `System.out::println`
REAL-LIFE APPLICATIONS:
- ✅ Printing collections with `forEach(System.out::println)`.
- ✅ Sorting with comparators (`String::compareToIgnoreCase`).
- ✅ Stream API transformations where existing methods suffice.
- ✅ Reusing existing utility methods (e.g., `Integer::parseInt` in a mapping function).
RULE OF THUMB:
- If your lambda only calls an existing method, prefer method references.
- Keeps code concise and more expressive.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 10a608c commit 762312f
1 file changed
+12
-18
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | 4 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
12 | 9 | | |
13 | 10 | | |
14 | 11 | | |
15 | 12 | | |
16 | | - | |
17 | | - | |
18 | | - | |
19 | | - | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
20 | 16 | | |
21 | 17 | | |
22 | 18 | | |
23 | | - | |
24 | | - | |
| 19 | + | |
25 | 20 | | |
26 | | - | |
| 21 | + | |
| 22 | + | |
27 | 23 | | |
28 | 24 | | |
29 | 25 | | |
| |||
32 | 28 | | |
33 | 29 | | |
34 | 30 | | |
35 | | - | |
36 | 31 | | |
37 | | - | |
38 | 32 | | |
39 | 33 | | |
40 | | - | |
| 34 | + | |
0 commit comments