Lamdba Expression
- Lambda expression is available in java from jdk 1.8 onwards.
- Lambda Expression is use to achieve functional programming in java language.
- Functional Interface are required to use lamdba expression.
- Lambda Expression symbol (->)
- Lambda Expression is a process where, you can provide implementation for abstract method from functional interface.
- In Lambda expression internally create and anonymous class and return the object of that class.
Build in Functional Interface
- Build-in functional interface is present inside java.util.function package.
- Predicate:
- This is an functional interface which is present inside java.util.function package
- This interface has test method which accept one value and return Boolean.
- This interface in use to write a condition (filtrations).
- Function
- This is an functional interface which is present inside java.util.function package
- This interface has apply method which accept one value and return another.
- This interface is use to convert your value from one form to another.
- Supplier
- This is an functional interface which is present inside java.util.function package
- This interface has get method which return value.
- This interface is use to perform the execution and return the out of execution.
- Consumer
- This is an functional interface which is present inside java.util.function package
- This interface has accept method which accept and input parameter and not return anything.
- This interface is use to perform the execution on input value and not return the output.
LambdaIntro :-
public class LambdaIntro { public static void main(String[] args) { Inter a = () -> { System.out.println("This is lambda Expression"); }; execute(a); } private static void execute(Inter a) { a.print(); } } @FunctionalInterface interface Inter { void print(); }
Example :-
public class LambdaDemo1 { public static void main(String[] args) { Inter1 i1 = (val) -> System.out.println("The value is "+ val); i1.print("Ram"); Inter2 i2 = (a, b) -> a+b; System.out.println(i2.add(12, 28)); Inter3 i3 = (a ,b) -> a-b; System.out.println(i3.sub(12, 28)); } } @FunctionalInterface interface Inter1 { public void print(String val); } @FunctionalInterface interface Inter2 { public int add(int a, int b); } @FunctionalInterface interface Inter3{ public int sub(int a, int b); }
Lambda Demo 2 :-
import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; public class LambdaDemo2 { public static void main(String[] args) { Predicate obj = (val) -> val%2==0; System.out.println(obj.test(12)); Predicate obj1 = (a) -> a%2==0; System.out.println(obj1.test(11)); System.out.println("============================="); Function obj2 = (num) -> num*num; System.out.println(obj2.apply(12)); Supplier obj3 = () -> { return 23*23; }; System.out.println(obj3.get()); } }
Join Telegram : Click Here
All Full Stack Java Study Material
Job’s For Fresher