Method References in Java 8 - Shaikh
Method References in Java 8 - Shaikh
Method references are a concise way to refer to methods or constructors without invoking them.
They provide a way to pass behavior as arguments to higher-order functions like lambdas.
Method references simplify code and improve readability by eliminating the need to write
complete lambda expressions for simple method calls.
Method references use the double colon `::` operator to reference a method or constructor. The
syntax varies based on the context in which method references are used:
**Examples:**
```java
// Lambda expression
Function<String, Integer> parseLambda = str -> Integer.parseInt(str);
// Method reference
Function<String, Integer> parseReference = Integer::parseInt;
```
```java
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Lambda expression
names.forEach(name -> System.out.println(name));
// Method reference
names.forEach(System.out::println);
```
3. **Constructor Reference:**
```java
// Lambda expression
Supplier<List<String>> listSupplierLambda = () -> new ArrayList<>();
// Constructor reference
Supplier<List<String>> listSupplierReference = ArrayList::new;
```
**Notes:**
- Method references provide a more compact and readable alternative to lambdas when the
lambda's sole purpose is to call a method or constructor.
- Method references can only be used with functional interfaces, where the method signature
matches the functional interface's abstract method.
- They help in promoting code reusability and modularity by encapsulating method behavior.
- Method references can simplify code when working with streams, making the code more
expressive and intuitive.
Method references are a valuable addition to Java 8, enhancing the functional programming
capabilities of the language while improving code readability and maintainability.