Lambda expression in java is a new and important feature of Java which was included in Java 8. lets see the what is lambda expression in java.
What is Lambda Expression in Java?
Lambda Expressions in Java are the way through which we can visualize functional programming in the object-oriented world. Objects are the basic building block of Java programming language, and we can never use a function without an object.
Therefore, Java provides support for using lambda expressions only with functional interfaces. We can implement a Java functional interface using Java Lambda Expression.
Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface.
Why do we need Lambda Expression in Java?
Reduced lines of code is one of the clear benefits of using a lambda expression.
Another advantage of using lambda expression is that we can get a Stream API sequential and parallel execution support.
We can use lambda expressions to pass the behavior of a method.
No parameters Program
interface interF2{
public int addition ();
}
public class LambdaFunctionEx1_WithoutParameter {
public static void main (String [] args) {
interF2 obj= () ->10+20+30+40+50;
System.out.println(“1) Addition =”+obj. addition ());
interF2 a= ()->{
System.out.println(“2) Test”);
int sum=80+90;
return sum;
}
System.out.println(“3) Addition = “+a. addition ());
}
}
Output:
1) Addition =150
2) Test
3) Addition = 170
Single Parameter Program
interface interF1{
public int lengthOfString (String str);
}
public class LambdaFunctionEx1_SingleParameter {
public static void main (String [] args) {
interF1 obj= str ->str.length();
int length=obj. lengthOfString(“Mumbai”);
int length1=obj.lengthOfString(“Pune”);
System.out.println(“1) Length of Mumbai =”+length);
System.out.println(“2) Length Of Pune =”+length1);
OutPut: –
1) Length of Mumbai =6
2) Length of Pune =4
Multiple Parameters Program
interface interF3{
public int addition (int a, float b);
}
public class LambdaFunctionEx1_MultipleParameter {
public static void main (String [] args) {
interF3 obj1=(x,y)->{ System.out.println(“1) Test”);
int sum=x+(int) y;
return sum;
};
System.out.println(“2) Addition = “+obj1.addition(25,20.78f));
OutPut:
1) Test
2) Addition = 45