Lambda Expression: Lambda expression is a simplest form of Functional interface implementation.
In how many ways we can implement a Functional Interface:
- Through class
- Through anonymous inner class
- Through lambda expression
Implement interface using class:
@FunctionalInterface interface First { void fun(); } class Second implements First { public void fun(){ System.out.println(“fun…”); } } class Main { public static void main(String[] args) { First obj = new Second(); obj.fun(); } } |
Through Anonymous inner class: Defining a class without identity is called Anonymous inner class. We always define anonymous class inside a method.
interface Test { void fun(); } class Main { public static void main(String[] args) { Test obj = new Test() { public void fun() { System.out.println(“Anonymous fun”); } }; obj.fun(); } } |
Through Lambda expression:
- Expression is a line of code.
- Lambda expression is the implementation of Functional Interface in a short format
@FunctionalInterface interface Test { void fun(); } class Main { public static void main(String[] args) { Test obj = () -> System.out.println(“Lambda fun”); obj.fun(); } } |
If the method not taking any parameter:
() -> expression |
If the method taking only one parameter:
parameter -> expression |
If the method taking more than one parameter:
(parameter1, parameter2) -> expression |
Lambda expression as block:
- Expressions immediately return a value, and they cannot contain variables, assignments or statements such as if or for.
- In order to do more complex operations, a code block can be used with curly braces.
- If the lambda expression needs to return a value, then the code block should have a return statement.
(parameter1, parameter2) -> { stat-1; stat-2; stat-3; return } |
Lamba expression with arguments:
- Lambda expression can take arguments based on the signature of method defined in functional interface.
- No need to specify the data types while representing the arguments in lambda expression.
@FunctionalInterface interface Calc { void add(int x, int y); } class Main { public static void main(String[] args) { Calc obj = (x, y) -> System.out.println(“Sum : ” + (x+y)); obj.add(5,3); obj.add(10,20); } } |
Lambda expression with return values: Lambda expression automatically returns the value which is evaluated in expression. We need to specify the return type in Functional Interface specification.
@FunctionalInterface interface Calc { int add(int x, int y); } class Main { public static void main(String[] args) { Calc obj = (x, y) -> x+y; System.out.println(“Sum : ” + obj.add(5,3)); System.out.println(“Sum : ” + obj.add(10,20)); } } |