Skip to content

Commit bd0ff20

Browse files
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

2 files changed

+13
-13
lines changed

JAVA8/MethodReference/src/MethodReference.java

Lines changed: 0 additions & 13 deletions
This file was deleted.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import java.util.Arrays;
2+
import java.util.List;
3+
4+
public class MethodReferenceDemo {
5+
public static void main(String[] args) {
6+
7+
// Method reference --> use a method without invoking and in place of a lambda expression
8+
List<String> students = Arrays.asList("Ram", "Shyam", "Tony");
9+
10+
//students.forEach(x -> System.out.println(x));
11+
students.forEach(System.out::println);
12+
}
13+
}

0 commit comments

Comments
 (0)