Following are some of the characteristics of lambda expression in Java 8.
1.It is a function which doesn’t have a name.But like other functions it has a :
- return type
- list of parameters
- body
2.lambda expression can be passed to other methods as parameters.This is a way to develop decoupled applications.
Since you can pass behaviour as a parameter using lambda expression at run time ,you are not coupling your application
to a fixed logic.This logic can be determined at runtime.
3.lambda expressions are easier to create than anonymous functions.
To create a lambda expression:
1.Create an interface with one abstract method called SayHello.Decorate the interface with annotation @FunctionalInterface.
@FunctionalInterface interface ExampleInterface { void SayHello(String data); }
2. Declare a lambda expression as:
Write parameters inside paranthesis.You should write the same number of parameters as declared in the above interface.
(String message)
3.Write arrow “-> ” and on the right hand side write the body of the lambda expression.
(String message)->System.out.println("hello "+message);
4.Declare an object of the interface type and assign the lambda expression to it
ExampleInterface f=(String message)->System.out.println("hello "+message);
5.Call the method of the interface using the object declared above.
f.SayHello("Java");
The above example prints the output hello Java.
Following is the complete example.
public class HelloWorld { public static void main(String[] args) { ExampleInterface f=(String message)->System.out.println("hello "+message); f.SayHello("Java"); } } @FunctionalInterface interface ExampleInterface { void SayHello(String data); }
In the above example of Lambda expression we have implemented a functional interface.Functional interface is an interface which has only one method.We can use lambda expression to implement different functionalities.
For example to add two number we use the following the example
Calculate f=(a,b)-> System.out.println(a+b);; f.Add(1,2); interface Calculate { void Add(int a,int b); }
Leave a Reply