Commit bd0ff20
committed
feat(method-references): add MethodReference demo using System.out::println
What
- Introduced `MethodReference` class demonstrating Java 8 method references.
- Created a list of student names (`Ram`, `Shyam`, `Tony`).
- Showcased:
- Traditional lambda expression for printing elements.
- Replacement with method reference `System.out::println` for cleaner syntax.
Why
- Method references provide a shorthand syntax for calling existing methods instead of writing explicit lambdas.
- They improve readability, reduce boilerplate, and make intent clearer when the lambda simply delegates to an existing method.
Logic
1. Created a `List<String>` using `Arrays.asList()`.
2. Demonstrated two approaches to iterate over the list:
- Lambda: `students.forEach(x -> System.out.println(x));`
- Method reference: `students.forEach(System.out::println);`
3. Both produce identical output, but method reference is more concise and idiomatic.
Real-life applications
- Commonly used in **Streams API** for cleaner code, e.g.:
- `list.stream().map(String::toUpperCase).forEach(System.out::println);`
- Helpful in **event-driven systems** (e.g., Swing, JavaFX, Spring callbacks).
- Used for **constructor references** (`ClassName::new`) in dependency injection frameworks.
- Useful when working with **functional interfaces** like `Consumer`, `Supplier`, `Function`, etc.
Notes
- Four types of method references in Java:
1. **Static methods** → `ClassName::staticMethod`.
2. **Instance methods of a particular object** → `instance::method`.
3. **Instance methods of an arbitrary object** → `ClassName::method`.
4. **Constructor references** → `ClassName::new`.
- Method references require the target method signature to match the functional interface’s abstract method signature.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5112423 commit bd0ff20
File tree
2 files changed
+13
-13
lines changed- JAVA8/MethodReference/src
- Java 8 Crash Course/Functional Interface/Default Methods/src
2 files changed
+13
-13
lines changedThis file was deleted.
Lines changed: 13 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
0 commit comments