0% found this document useful (0 votes)
13 views

Method References in Java 8 - Shaikh

Uploaded by

Java Developer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Method References in Java 8 - Shaikh

Uploaded by

Java Developer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

**Method References in Java 8**

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.

**Syntax of Method References:**

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:

1. **Reference to a Static Method:** `ClassName::staticMethodName`


2. **Reference to an Instance Method of a Particular Object:** `instance::instanceMethodName`
3. **Reference to an Instance Method of an Arbitrary Object of a Particular Type:**
`ClassName::instanceMethodName`
4. **Reference to a Constructor:** `ClassName::new`

**Examples:**

1. **Static Method Reference:**

```java
// Lambda expression
Function<String, Integer> parseLambda = str -> Integer.parseInt(str);

// Method reference
Function<String, Integer> parseReference = Integer::parseInt;
```

2. **Instance Method Reference:**

```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.

You might also like