Java 8 introduced benefits of Functional Programming in java.
Lambda Expression : Lambda is an anonymous function in java , a function without name ,return type and access modifier.
In java , normally we write method as below :
Example :Without Lambda
public void run(){
System.out.println("Welcome to www.crtr4u.com");
}
using lambda expression same method can be written as: ()->System.out.println("Welcome to www.crtr4u.com");
if we have multiple statements then we can use brackets,
Lambda Expression also known as anonymous function or closures.Example : without using lambda :
public void add(int num1,int num2){
System.out.println(num1+num2);
}
above example can be written using lambda expression as : (int num1,int num2)->System.out.println(num1+num2);
Why To Use Lambda Expression : 1.Easy to implement and Less Code as shown in above example.
2.We can pass lambda expression as paramater to other method.
To implement Lambda Expression in java , we have to use Functional Interface.
Functional Interface is an interface with only one abstract method,we can create our own functional interface by using annotation @FunctionalInterface.
Note - we can add many defaults method in functional interface , but only one abstract method.
Addition Example Using Lambda Expression :
@FunctionalInterface
interface DemoInterface{
public void add(int a,int b);
}
public class Java8Demo {
public static void main(String[] args) {
DemoInterface d=(a,b)->System.out.println("Addition is "+(a+b));
d.add(1, 2);
d.add(4, 7);
}
}
Output : Addition is 3
Addition is 11
Program to check Even or Odd number using Functional Interface , Lambda Expression in Java :
Example :
Output : public class Java8Demo {
public static void main(String[] args) {
EvenOddDemo d = (num) -> {
if (num % 2 == 0)
System.out.println("Even number : " + (num));
else
System.out.println("Odd number : " + (num));
};
d.isEvenOrOdd(5);
d.isEvenOrOdd(12);
}
}
@FunctionalInterface
interface EvenOddDemo {
public void isEvenOrOdd(int a);
}
Odd number : 5
Even number : 12