- Java – It supports OOPs & FP paradigm.
- Based on oops,
- Everything in java are objects, except primitive data types.
- We need object references to call any method.
- In Functional Programming,
- Purpose: Concise coding
- Do not need object creations.
LAMBDA EXPRESSIONS:
- Lambda expression is a new feature which is introduced in Java 8.
- A lambda expression is an anonymous function (function – method).
- Anonymous means nameless.
- Anonymous function doesn’t contain,
- access modifier – All methods are public by default
- return data type
- function name
- Lambda expression is used to provide the implementation of functional interface.
- Do not need a class for implementing functional interface.
- So, it saves lots of coding efforts.
FUNCTIONAL INTERFACE:
- An interface with only single abstract method is called functional interface.
- Functional interface contains,
- Single abstract method
- n number of default methods
- n number of static methods
- Predefined functional interface:
- runnable
- callable
- comparable, etc.
- In user defined functional interface, before declaring interface name, mention @FunctionalInterface annotation.
Annotation:
- Java Annotation is a kind of a tag that represents the information attached with class, interface, methods, or fields to show some additional information that Java compiler and JVM can use.
Normal Vs Anonymous function:
//Normal Method
public void add()
{
System.out.println(5+5);
}
---------------------------
//ANONYMOUS METHOD
()->
{
System.out.println(5+5);
};
---------------------------
Ex 1:
@FunctionalInterface
public interface MyFunctionalInterface {
public abstract void add();
public static void multiple()
{
System.out.println(5*2);
}
default void divide()
{
System.out.println(10/2);
}
}
public class Demo {
public static void main(String[] args)
{
MyFunctionalInterface handle = ()-> System.out.println(5+5);
handle.add();
handle.divide();
MyFunctionalInterface.multiple();
}
}
Output:
10
5
10
NOTE:
- Here, we do not implement the functional interface by class.
Ex 2:
@FunctionalInterface
public interface MyFunctionalInterface
{
public abstract int add(int a, int b);
}
public class Demo {
public static void main(String[] args)
{
MyFunctionalInterface handle = (int no1,int no2)-> no1+no2;
int result = handle.add(40,50);
System.out.println(result);
}
}
Output:
90