Saturday, September 23, 2017

Lambda (Java 8) - Interface Implementation

In this post, I'm going to describe the way, we use lamdba to 'Interface Implementation'.

Find the below steps:

1. Create an interface as below
public interface Greeting {
    void perform() ;
}

2. In lambda, you can implement the perform method as below
Greeting greeting = () -> System.out.println("Hello Greeting");

3. Then finally, you can invoke the perform method as below.
...
Greeting greeting = () -> System.out.println("Hello , Greeting");
greeting.perform();
...
In the above scenario, I used empty parentheses, it is because, it should be similar to the method signature.
For an example, If I declare the perform() as perform(String message), lambda expression should be as below.
Greeting greeting = (message) -> System.out.println("Hello " + message);

Note: Here we don't need to specify the parameter type, java automatically sets the relevant type.

When we have a return type, above sample should change like follows.

public interface Greeting {
    String perform(String message) ;
}
Lambda:
Greeting greeting = (message) -> "Hello " + message;
Then, when we execute the perform method, it returns a string value.

Note: If you have to pass a single parameter, you can remove the parentheses as below
Greeting greeting = message -> "Hello " + message;

Enjoy...!!

No comments:

Post a Comment